fprintf fscanf等函式的用法
對檔案的讀和寫是最常用的檔案操作。在C語言中提供了多種檔案讀寫的函式:
·字元讀寫函式 :fgetc和fputc
·字串讀寫函式:fgets和fputs
·資料塊讀寫函式:fread和fwrite
·格式化讀寫函式:fscanf和fprinf
隨著每次資料的讀取,檔案流指標fp都作相應的移動
使用以上函式都要求包含標頭檔案stdio.h。例子都來自msdn
1 fprintf——Print formatted data to a stream
#include <stdio.h>
#include <process.h>
FILE *stream;
void main( void )
{
int i = 10;
double fp = 1.5;
char s[] = "this is a string";
char c = '/n';
stream = fopen( "fprintf.out", "w" );
fprintf( stream, "%s%c", s, c );
fprintf( stream, "%d/n", i );
fprintf( stream, "%f/n", fp );
fclose( stream );
system
}
Output
this is a string
10
1.500000
2 fscanf——Read formatted data from a stream
#include <stdio.h> FILE *stream; void main( void ) { long l; float fp; char s[81]; char c; stream = fopen( "fscanf.out", "w+" ); if( stream == NULL ) printf( "The file fscanf.out was not opened/n" ); else { fprintf( stream, "", "a-string", 65000, 3.14159, 'x' ); /* Set pointer to beginning of file: */ ( stream, 0L, SEEK_SET ); /* Read data back from file: */ fscanf( stream, "%s", s ); fscanf( stream, "%ld", &l ); fscanf( stream, "%f", &fp ); fscanf( stream, "%c", &c ); /* Output data read: */ printf( "%s/n", s ); printf( "%ld/n", l ); printf( "%f/n", fp ); printf( "%c/n", c ); fclose( stream ); } }
Output
a-string
65000
3.141590
x
3 fread——Reads data from a stream
4 fwrite——Writes data to a stream
讀資料塊函式呼叫的一般形式為:
fread(buffer,size,count,fp);
寫資料塊函式呼叫的一般形式為:
fwrite(buffer,size,count,fp);
其中:
buffer 是一個指標,在fread函式中,它表示存放輸入資料的首地址。在fwrite函式中,它表示存放輸出資料的首地址。
size 表示資料塊的位元組數。
count 表示要讀寫的資料塊塊數。
fp 表示檔案指標。
5 fgets 沒有看出與fread太大的區別,除了fread可以處理string外的其他不同檔案的資料型別
6 fputs
7 fgetc fputs
從鍵盤輸入一行字元,寫入一個檔案,再把該檔案內容讀出顯示在螢幕上。
#i nclude
main()
{
FILE *fp;
char ch;
if((fp=fopen("d://jrzh//example//string","wt+"))==NULL)
{
printf("Cannot open file strike any key exit!");
getch();
exit(1);
}
printf("input a string:/n");
ch=getchar();
while (ch!='/n')
{
fputc(ch,fp);
ch=getchar();
}
rewind(fp); //Repositions the file pointer to the beginning of a file
ch=fgetc(fp);
while(ch!=EOF)
{
putchar(ch);
ch=fgetc(fp);
}
printf("/n");
fclose(fp);
}