標籤:style blog http color os ar for 檔案 2014
C lib的檔案操作是獨立於具體的作業系統平台的
1. 建立和開啟
FILE *fopen(const char *path, const char *mode);
fopen()實現開啟指定檔案filename,其中的mode為開啟模式,C lib中支援開啟的mode如下:
其中b用於區分二進位檔案和文字檔。
2. 讀寫
C lib支援以字元、字串等為單位,支援按照某種格式進行讀寫,
int fgetc(FILE *stream);int fputc(int c, FILE *stream);char *fgets(char *s, int n, FILE *stream);int fputs(const char *s, FILE *stream);int fprintf(FILE *stream, const char *format, ...);int fscanf(FILE *stream, const char *format, ...);size_t fread(void *ptr, size_t size, size_t n, FILE *stream);size_t fwrite(const void *ptr, size_t size, size_t n, FILE *stream);
fread()實現從流stream中讀取n個欄位,每個欄位為size位元組,並將讀取的欄位放入ptr所指的字元數組中,返回已讀的地段數,
在讀取的欄位數小於n時有兩種情況,第一就是函數出現錯誤,可用ferror()來判斷, 第二就是讀到檔案的結尾,可用feof()來判斷。
write()實現從緩衝區ptr所指的數組中把n個欄位的size位元組寫到stream流中,返回實際寫入的欄位數。
另外,C lib提供了讀寫的定位函數:
int fgetpos(FILE *stream, fpos_t *pos);int fsetpos(FILE *stream, const fpos_t *pos);int fseek(FILE *stream, long offset, int whence);
3. 關閉
int fclose(FILE);
C庫檔案操作