Example: FILE *myfile; |
在C中,實際上是使用Stream I/O的方式來存取資料。也就是說,當打開一個檔案後, OS那邊會將一部分的資料先讀起來在一個暫存的Buffer裡,然後FILE這個pointer就會去指向這個buffer, 每讀取一個字元時,它就會往前移動一個。同樣的,當我們在寫入的時候,當我們完成像是fprintf時, 它也是先寫入這個buffer中,直到這個buffer被flush或是寫出到device中,才會真正的做改變。

這張圖的左邊就是device;右邊就是buffer。
| "r" | open for reading; 假如檔案不存在,則失敗。 |
| "w" | open or create for writing; 假如檔案存在,其現存的內容會被覆蓋。 |
| "a" | open or create for writng; 看w的不同在於,它會接著現存的內容繼續做下去 |
| "r+" | open for reading and writing; 檔案一定要存在 |
| "w+" | open or create for reading and writing; 檔案不存在就開新檔案,存在就覆寫 |
| "a+" | open or create for reading and writing; 不同處同上面a和w的差別 |
| FILE *fopen(char *name, char *mode) |
Example:
FILE *myfile;myfile = fopen("input.txt", "r");
|
Syntax:
int feof( FILE *stream );
|
| Example: if( feof( myfile ) )
printf("End of file\n");
|
Syntax:
int fgetc( FILE *stream );int fputc( int c, FILE *stream );
|
Example:
FILE *myfile, *myfile2;
int c;
myfile = fopen("in", "r");>
myfile2 = fopen("out", "w");
while( (c=fgetc(myfile)) != EOF)
fputc(c, myfile2);
|
Syntax:
char *fgets(char *str, int size, FILE *stream);int fputs(const char *str, FILE *stream);
|
Example:
FILE *myfile, *myfile2;
char tmp[80];
myfile = fopen("in", "r");>
myfile2 = fopen("out", "w");
while( (fgets(tmp, 80, myfile)) != NULL)
fputs(tmp, myfile2);
|
Examples: fprintf(outputfile, "My age is %d\n", myAge); fscanf(inputfile, "%f", &floatVariable); |
Syntax:
int fclose( FILE *stream );
|
#include |