C語言檔案操作詳解
阿新 • • 發佈:2018-12-29
* 檔案狀態檢查
A. 檔案結束
(1) 函式原型
int feof(FILE *fp)
(2) 功能說明
該函式用來判斷檔案是否結束。
(3) 引數說明
fp:檔案指標。
(4) 返回值
0:假值,表示檔案未結束。
1:真值,表示檔案結束。
(5) 例項
【例8.10】
- #include <stdio.h>
- void main(int argc,char *argv[])
- {
- FILE *in,*out;
- char ch;
-
if(argc!=3)
- {
- printf("Usage: copyfile filename1 filename2\n");
- return;
- }
- if((in=fopen(argv[1],"rb"))==NULL)
- {
- printf("The file %s can not be opened.\n",argv[1]);
- return;
- }
- if((out=fopen(argv[2],"wb"))==NULL)
- {
-
printf("The file %s can not be opened.\n"
- return;
- }
- while(!feof(in))
- {
- ch=fgetc(in);
- if(ferror(in))
- {
- printf("read error!\n");
- clearerr(in);
- }
- else
- {
- fputc(ch,out);
-
if(ferror(out))
- {
- printf("write error!\n");
- clearerr(out);
- }
- }
- }
- fclose(in);
- fclose(out);
- }
B. 檔案讀/寫出錯
(1) 函式原型
int ferror(FILE *fp)
(2) 功能說明
檢查由fp指定的檔案在讀寫時是否出錯。
(3) 引數說明
fp:檔案指標。
(4) 返回值
0:假值,表示無錯誤。
1:真值,表示出錯。
C. 清除檔案錯誤標誌
(1) 函式原型
void clearerr(FILE *fp)
(2) 功能說明
清除由fp指定檔案的錯誤標誌。
(3) 引數說明
fp:檔案指標。
(4) 返回值
無。
(5) 例項
【例8.12】
- #include <stdio.h>
- void main(int argc,char *argv[])
- {
- FILE *in,*out;
- char ch;
- if(argc!=3)
- {
- printf("Usage: copyfile filename1 filename2\n");
- return;
- }
- if((in=fopen(argv[1],"rb"))==NULL)
- {
- printf("The file %s can not be opened.\n",argv[1]);
- return;
- }
- if((out=fopen(argv[2],"wb"))==NULL)
- {
- printf("The file %s can not be opened.\n",argv[2]);
- return;
- }
- while(!feof(in))
- {
- ch=fgetc(in);
- if(ferror(in))
- {
- printf("read error!\n");
- clearerr(in);
- }
- else
- {
- fputc(ch,out);
- if(ferror(out))
- {
- printf("write error!\n");
- clearerr(out);
- }
- }
- }
- fclose(in);
- fclose(out);
- }
D. 瞭解檔案指標的當前位置
(1) 函式原型
long ftell(FILE *fp)
(2) 功能說明
取得由fp指定檔案的當前讀/寫位置,該位置值用相對於檔案開頭的位移量來表示。
(3) 引數說明
fp:檔案指標。
(4) 返回值
正常返回:位移量(這是個長整數)。
異常返回:-1,表示出錯。
(5) 例項
* 檔案定位
A. 反繞
(1) 函式原型
void rewind(FILE *fp)
(2) 功能說明
使由檔案指標fp指定的檔案的位置指標重新指向檔案的開頭位置。
(3) 引數說明
fp:檔案指標。
(4) 返回值
無。
(5) 例項
【例8.14】
- #include <stdio.h>
- void main()
- {
- FILE *in,*out;
- in=fopen("filename1","r");
- out=fopen("filename2","w");
- while(!feof(in)) fputc(fgetc(in),out);
- rewind(out);
- while(!feof(in)) putchar(fgetc(in));
- fclose(in);
- fclose(out);
- }
B. 隨機定位
(1) 函式原型