教你徹底學會c語言基礎——檔案操作

函式介紹
檔案開啟與關閉操作
fopen():檔案開啟操作
標頭檔案:stdio.h
函式定義:FILE *fopen(char *pname, char *mode)
函式說明:pname是檔名,mode是開啟檔案的方式
mode:"r" 開啟一個已經存在的檔案文字,檔案不存在則出錯

以“r+”的方式開啟一個檔案,會清空檔案的原始內容,重新寫入資料
返回值:正常返回:FILE *一個指向檔案在記憶體中的檔案資訊去的開頭
異常返回:NULL,表示開啟操作不成功
開啟檔案的作用是:
(1)分配給開啟檔案一個FILE 型別的檔案結構體變數,並將有關資訊填入檔案結構體變數;
(2)開闢一個緩衝區;
(3)呼叫作業系統提供的開啟檔案或建立新檔案功能,開啟或建立指定檔案;
FILE *:指出fopen是一個返回檔案型別的指標函式;
返回值
正常返回:被開啟檔案的檔案指標。
異常返回:NULL,表示開啟操作不成功。
要說明的是:C語言將計算機的輸入輸出裝置都看作是檔案。例如,鍵盤檔案、螢幕檔案等。ANSI C標準規定,在執行程式時系統先自動開啟鍵盤、螢幕、錯誤三個檔案。這三個檔案的檔案指標分別是:標準輸入stdin、標準輸出stdout和標準出錯 stderr。
fclose():檔案關閉
函式定義:int fclose(FILE *fp);
函式說明:fp是一個以開啟的檔案的檔案指標
返回值:
正常返回:0
異常返回:EOF,表示檔案在關閉時發生錯誤
fgetc:讀取一個字元
函式定義:int fgetc(FILE *fp)
函式說明:從fp中讀取一個字元,作為返回值返回
返回值:
正常返回:返回讀取字元的程式碼
異常返回:返回EOF。例如:要從“寫開啟”的檔案中讀取一個字元時,會發生錯誤而返回一個EOF
【例1】顯示指定檔案的內容。
//程式名為:display.c
//執行時可用:display filename1 形式的命令列執行。顯示檔案filename1中的內容。例如,執行命令列display display.c將在螢幕上顯示display的原始碼。
//File display program.
#include
void main(int argc,char *argv[]) //命令列引數
{
int ch;//定義檔案型別指標
FILE *fp;//判斷命令列是否正確
if(argc!=2)
{
printf("Error format,Usage: display filename1");
return; //鍵入了錯誤的命令列,結束程式的執行
}
//按讀方式開啟由argv[1]指出的檔案
if((fp=fopen(argv[1],"r"))==NULL)
{
printf("The file <%s> can not be opened.",argv[1]);//開啟操作不成功
return;//結束程式的執行
}
//成功打開了argv[1]所指檔案
ch=fgetc(fp); //從fp所指檔案的當前指標位置讀取一個字元
while(ch!=EOF) //判斷剛讀取的字元是否是檔案結束符
{
putchar(ch); //若不是結束符,將它輸出到螢幕上顯示
ch=fgetc(fp); //繼續從fp所指檔案中讀取下一個字元
} //完成將fp所指檔案的內容輸出到螢幕上顯示
fclose(fp); //關閉fp所指檔案
}
fputc:寫一個字元到檔案中
函式定義:int fputc(int ch, FILE*fp)
函式說明:ch是一個整型變數,要寫到檔案的字元
fp:檔案指標,要寫入的檔案
返回值:
正常返回:要寫入的字元的程式碼
異常返回:返回EOF
【例2】將一個檔案的內容複製到另一個檔案中去。
//程式名為:copyfile.c
//執行時可用:copyfile filename1 filename2形式的命令列執行,將檔案filename1中的內容複製到檔案filename2中去。
//file copy program.
#include
void main(int argc,char *argv[]) //命令列引數
{
int ch;
FILE *in,*out; //定義in和out兩個檔案型別指標
if(argc!=3) //判斷命令列是否正確
{
printf("Error in format,Usage: copyfile filename1 filename2");
return; //命令列錯,結束程式的執行
}
//按讀方式開啟由argv[1]指出的檔案
if((in=fopen(argv[1],"r"))==NULL)
{
printf("The file <%s> can not be opened.",argv[1]);
return; //開啟失敗,結束程式的執行
}
//成功打開了argv[1]所指檔案,再
//按寫方式開啟由argv[2]指出的檔案
if((out=fopen(argv[2],"w"))==NULL)
{
printf("The file %s can not be opened.",argv[2]);
return; //開啟失敗,結束程式的執行
}
//成功打開了argv[2]所指檔案
ch=fgetc(in); //從in所指檔案的當前指標位置讀取一個字元
while(ch!=EOF) //判斷剛讀取的字元是否是檔案結束符
{
fputc(ch,out); //若不是結束符,將它寫入out所指檔案
ch=fgetc(in); //繼續從in所指檔案中讀取下一個字元
} //完成將in所指檔案的內容寫入(複製)到out所指檔案中
fclose(in); //關閉in所指檔案
fclose(out); //關閉out所指檔案
}
【例3】按十進位制和字元顯示檔案程式碼,若遇不可示字元就用井號"#"字元代替之。
//程式名為:dumpf.c
//執行時可用:dumpf filename1 形式的命令列執行。
// File dump program.
#include
void main(int argc,char *argv[])
{
char str[9];
int ch,count,i;
FILE *fp;
if(argc!=2)
{
printf("Error format,Usage: dumpf filename");
return;
}
if((fp=fopen(argv[1],"r"))==NULL)
{
printf("The file %s can not be opened.",argv[1]);
return;
}
count=0;
do{
i=0;
//按八進位制輸出第一列,作為一行八個位元組的首地址
printf("%06o: ",count*8);
do{
// 從開啟的檔案中讀取一個字元
ch=fgetc(fp);
// 按十進位制方式輸出這個字元的ASCII碼
printf("%4d",ch);
// 如果是不可示字元就用"#"字元代替
if(ch<' '||ch>'~') str[i]='#';
// 如果是可示字元,就將它存入陣列str以便形成字串
else str[i]=ch;
// 保證每一行輸出八個字元
if(++i==8) break;
}while(ch!=EOF); // 遇到檔案尾標誌,結束讀檔案操作
str[i]=''; // 在陣列str加字串結束標誌
for(;i<8;i++) printf(" "); // 一行不足八個字元用空格填充
printf(" %s",str); // 輸出字串
count++; // 準備輸出下一行
}while(ch!=EOF); // 直到檔案結束
fclose(fp); // 關閉fp所指檔案
}

小編給大家推薦一個學習氛圍超好的地方,C/C++交流企鵝裙:870963251!適合在校大學生,小白,想轉行,想通過這個找工作的加入。裙裡有大量學習資料,有大神解答交流問題,每晚都有免費的直播課程
fgets():從檔案中讀取一個字串
函式定義:char *fgets(char *str, int n, FILE *fp)
函式說明:由fp指出的檔案中讀取n-1個字元,並把他們存放到有str指出的字元陣列中區,最後加上一個由字串結束符''
引數說明:str:接受字串的記憶體地址,可以是數組別名,也可以是指標
n:指出要讀取的字元的個數
fp:這個是檔案指標,指出要從中讀取字元的檔案
返回值:
正常返回:字串的記憶體首地址,即str的值
異常返回:返回一個NULL值,此時應當用feof()或ferror()函式來判別是讀取到了檔案尾,還是發生了錯誤。
fputs():寫入字串到檔案中去
函式定義:把由str之處的字串寫入到fp所指的檔案中去
函式說明:
str:之處要寫入到檔案中去的字串,不包括最後的''
fp:這個是檔案指標,之處字串要寫入到的檔案指標
返回值:
正常返回:寫入到的檔案的字元個數,即字串的長度
非正常返回:返回一個NULL值,此時應當用feof()或ferror()函式來判別是讀取到了檔案尾,還是發生了錯誤。
5.例項
【例4】以下程式將一個檔案的內容附加到另一個檔案中去。
//程式名:linkfile.c
//執行時可用:linkfile filename1 filename2形式的命令列執行,將檔案filename2的內容附加在檔案filename1之後。
// file linked program.
#include
#define SIZE 512
void main(int argc,char *argv[])
{
char buffer[SIZE];
FILE *fp1,*fp2;
if(argc!=3)
{
printf("Usage: linkfile filename1 filename2");
return;
}
// 按追加方式開啟argv[1] 所指檔案
if((fp1=fopen(argv[1],"a"))==NULL)
{
printf("The file %s can not be opened.",argv[1]);
return;
}
if((fp2=fopen(argv[2],"r"))==NULL)
{
printf("The file %s can not be opened.",argv[2]);
return;
}
// 讀入一行立即寫出,直到檔案結束
while(fgets(buffer,SIZE,fp1)!=NULL)
printf("%s",buffer);
while(fgets(buffer,SIZE,fp2)!=NULL)
fputs(buffer,fp1);
fclose(fp1);
fclose(fp2);
if((fp1=fopen(argv[1],"r"))==NULL)
{
printf("The file %s can not be opened.",argv[1]);
return;
}
while(fgets(buffer,SIZE,fp1)!=NULL)
printf("%s",buffer);
fclose(fp1);
}
E. 往檔案中寫格式化資料
1.函式原型
int fprintf(FILE *fp,char *format,arg_list)
2.功能說明
將變量表列(arg_list)中的資料,按照format指出的格式,寫入由fp指定的檔案。fprintf()函式與printf()函式的功能相同,只是printf()函式是將資料寫入螢幕檔案(stdout)。
3.引數說明
fp:這是個檔案指標,指出要將資料寫入的檔案。
format:這是個指向字串的字元指標,字串中含有要寫出資料的格式,所以該字串成為格式串。格式串描述的規則與printf()函式中的格式串相同。
arg_list:是要寫入檔案的變量表列,各變數之間用逗號分隔。
4.返回值
無。
5. 例項
【例5】下列程式的執行檔案為display.exe,執行時鍵入命令列:
display [-i][-s] filename
下面的表格列出了命令列引數的含義及其功能:
//儲存檔名:save.txt
//程式程式碼如下:
// file display program.
#include
void main()
{
char name[10];
int nAge,nClass;
long number;
FILE *fp;
if((fp=fopen("student.txt","w"))==NULL)
{
printf("The file %s can not be opened.","student.txt");
return;
}
fscanf(stdin,"%s %d %d %ld",name,&nClass,&nAge,&number);
fprintf(fp,"%s %5d %4d %8ld",name,nClass,nAge,number);
fclose(fp);
if((fp=fopen("student.txt","r"))==NULL)
{
printf("The file %s can not be opened.","student.txt");
return;
}
fscanf(fp,"%s %d %d %ld",name,&nClass,&nAge,&number);
printf("name nClass nAge number");
fprintf(stdout,"%-10s%-8d%-6d%-8ld",name,nClass,nAge,number);
fclose(fp);
}
G. 以二進位制形式讀取檔案中的資料
1. 函式原型
int fread(void *buffer,unsigned sife,unsigned count,FILE *fp)
2. 功能說明
從由fp指定的檔案中,按二進位制形式將sife*count個數據讀到由buffer指出的資料區中。
3. 引數說明
buffer:這是一個void型指標,指出要將讀入資料存放在其中的儲存區首地址。
sife:指出一個數據塊的位元組數,即一個數據塊的大小尺寸。
count:指出一次讀入多少個數據塊(sife)。
fp:這是個檔案指標,指出要從其中讀出資料的檔案。
4.返回值
正常返回:實際讀取資料塊的個數,即count。
異常返回:如果檔案中剩下的資料塊個數少於引數中count指出的個數,或者發生了錯誤,返回0值。此時可以用feof()和ferror()來判定到底出現了什麼
情況。
H. 以二進位制形式寫資料到檔案中去
1. 函式原型
int fwrite(void *buffer,unsigned sife,unsigned count,FILE *fp)
2. 功能說明
按二進位制形式,將由buffer指定的資料緩衝區內的sife*count個數據寫入由fp指定的檔案中去。
3. 引數說明
buffer:這是一個void型指標,指出要將其中資料輸出到檔案的緩衝區首地址。
sife:指出一個數據塊的位元組數,即一個數據塊的大小尺寸。
count:一次輸出多少個數據塊(sife)。
fp:這是個檔案指標,指出要從其中讀出資料的檔案。
4.返回值
正常返回:實際輸出資料塊的個數,即count。
異常返回:返回0值,表示輸出結束或發生了錯誤。
5.例項
【例6】
#include
#define SIZE 4
struct worker
{ int number;
char name[20];
int age;
};
void main()
{
struct worker wk;
int n;
FILE *in,*out;
if((in=fopen("file1.txt","rb"))==NULL)
{
printf("The file %s can not be opened.","file1.txt");
return;
}
if((out=fopen("file2.txt","wb"))==NULL)
{
printf("The file %s can not be opened.","file2.txt");
return;
}
while(fread(&wk,sizeof(struct worker),1,in)==1)
fwrite(&wk,sizeof(struct worker),1,out);
fclose(in);
fclose(out);
}
I. 以二進位制形式讀取一個整數
1. 函式原型
int getw(FILE *fp)
2. 功能說明
從由fp指定的檔案中,以二進位制形式讀取一個整數。
3. 引數說明
fp:是檔案指標。
4. 返回值
正常返回:所讀取整數的值。
異常返回:返回EOF,即-1。由於讀取的整數值有可能是-1,所以必須用feof()或ferror()來判斷是到了檔案結束,還是出現了一個出錯。
5. 例項
【例7】
#include
void main(int argc,char *argv[])
{
int i,sum=0;
FILE *fp;
if(argc!=2)
{
printf("Command error,Usage: readfile filename");
exit(1);
}
if(!(fp=fopen(argv[1],"rb")))
{
printf("The file %s can not be opened.",argv[1]);
exit(1);
}
for(i=1;i<=10;i++) sum+=getw(fp);
printf("The sum is %d",sum);
fclose(fp);
}

J. 以二進位制形式存貯一個整數
1.函式原型
int putw(int n,FILE *fp)
2. 功能說明
以二進位制形式把由變數n指出的整數值存放到由fp指定的檔案中。
3. 引數說明
n:要存入檔案的整數。
fp:是檔案指標。
4. 返回值
正常返回:所輸出的整數值。
異常返回:返回EOF,即-1。由於輸出的整數值有可能是-1,所以必須用feof()或ferror()來判斷是到了檔案結束,還是出現了一個出錯。
5. 例項
【例8】
#include
void main(int argc,char *argv[])
{
int i;
FILE *fp;
if(argc!=2)
{
printf("Command error,Usage: writefile filename");
return;
}
if(!(fp=fopen(argv[1],"wb")))
{
printf("The file %s can not be opened.",argv[1]);
return;
}
for(i=1;i<=10;i++) printf("%d", putw(i,fp));
fclose(fp);
}
* 檔案狀態檢查
A. 檔案結束
(1) 函式原型
int feof(FILE *fp)
(2) 功能說明
該函式用來判斷檔案是否結束。
(3) 引數說明
fp:檔案指標。
(4) 返回值
0:假值,表示檔案未結束。
1:真值,表示檔案結束。
(5) 例項
【例9】
#include
void main(int argc,char *argv[])
{
FILE *in,*out;
char ch;
if(argc!=3)
{
printf("Usage: copyfile filename1 filename2");
return;
}
if((in=fopen(argv[1],"rb"))==NULL)
{
printf("The file %s can not be opened.",argv[1]);
return;
}
if((out=fopen(argv[2],"wb"))==NULL)
{
printf("The file %s can not be opened.",argv[2]);
return;
}
while(!feof(in))
{
ch=fgetc(in);
if(ferror(in))
{
printf("read error!");
clearerr(in);
}
else
{
fputc(ch,out);
if(ferror(out))
{
printf("write error!");
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) 例項
【例10】
#include
void main(int argc,char *argv[])
{
FILE *in,*out;
char ch;
if(argc!=3)
{
printf("Usage: copyfile filename1 filename2");
return;
}
if((in=fopen(argv[1],"rb"))==NULL)
{
printf("The file %s can not be opened.",argv[1]);
return;
}
if((out=fopen(argv[2],"wb"))==NULL)
{
printf("The file %s can not be opened.",argv[2]);
return;
}
while(!feof(in))
{
ch=fgetc(in);
if(ferror(in))
{
printf("read error!");
clearerr(in);
}
else
{
fputc(ch,out);
if(ferror(out))
{
printf("write error!");
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) 例項
【例11】
#include
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) 函式原型
int fseek(FILE *fp,long offset,int base)
(2) 功能說明
使檔案指標fp移到基於base的相對位置offset處。
(3)引數說明
fp:檔案指標。
offset:相對base的位元組位移量。這是個長整數,用以支援大於64KB的檔案。
base:檔案位置指標移動的基準位置,是計算檔案位置指標位移的基點。ANSI C定義了base的可能取值,以及這些取值的符號常量。
(4)返回值
正常返回:當前指標位置。
異常返回:-1,表示定位操作出錯。
(5)例項
【例12】
#include
#include
struct std_type
{
int num;
char name[20];
int age;
char class;
}stud;
int cstufile()
{
int i;
FILE *fp;
if((fp=fopen("stufile","wb"))==NULL)
{
printf("The file can't be opened for write.");
return 0;
}
for(i=1;i<=100;i++)
{
stud.num=i;
strcpy(stud.name,"aaaa");
stud.age=17;
stud.class='8';
fwrite(&stud,sizeof(struct std_type),1,fp);
}
fclose(fp);
return 1;
}
void main()
{
int n;
FILE *fp;
if(cstufile()==0) return;
if((fp=fopen("stufile","rb"))==NULL)
{
printf("The file can not be opened.");
return;
}
for(n=0;n<100;n+=2)
{
fseek(fp,n*sizeof(struct std_type),SEEK_SET);
fread(&stud,sizeof(struct std_type),1,fp);
printf("%10d%20s%10d%4c",stud.num,stud.name,stud.age,stud.class);
}
fclose(fp);
}
* 關於exit()函式
1. 函式原型
void exit(int status)
2. 功能說明
exit()函式使程式立即終止執行,同時將緩衝區中剩餘的資料輸出並關閉所有已經開啟的檔案。
3. 引數說明
status:為0值表示程式正常終止,為非0值表示一個定義錯誤。
4. 返回值
無。
* 關於feof()函式
1. 函式原型
int feof(FILE *fp)
2. 功能說明
在文字檔案(ASCII檔案)中可以用值為-1的符號常量EOF來作為檔案的結束符。但是在二進位制檔案中-1往往可能是一個有意義的資料,因此不能用它 來作為檔案的結束標誌。為了能有效判別檔案是否結束,ANSI C提供了標準函式feof(),用來識別檔案是否結束。
3. 引數說明
fp:檔案指標。
4. 返回值
返回為非0值:已到檔案尾。
返回為0值:表示還未到檔案尾