fwrite函數(shù)的一般調(diào)用形式是“fwrite(buffer,size,count,fp);”;其中,buffer是準(zhǔn)備輸出的數(shù)據(jù)塊的起始地址,size是每個(gè)數(shù)據(jù)塊的字節(jié)數(shù),count用來指定每寫一次或輸出的數(shù)據(jù)塊,fp為文件指針。
fwrite() 是C 語言標(biāo)準(zhǔn)庫中的一個(gè)文件處理函數(shù),功能是向指定的文件中寫入若干數(shù)據(jù)塊,如成功執(zhí)行則返回實(shí)際寫入的數(shù)據(jù)塊數(shù)目。該函數(shù)以二進(jìn)制形式對文件進(jìn)行操作,不局限于文本文件。
語法:
fwrite(buffer,size,count,fp)
參數(shù):
-
buffer是準(zhǔn)備輸出的數(shù)據(jù)塊的起始地址
-
size是每個(gè)數(shù)據(jù)塊的字節(jié)數(shù)
-
count用來指定每寫一次或輸出的數(shù)據(jù)塊
-
fp為文件指針。
函數(shù)返回寫入數(shù)據(jù)的個(gè)數(shù)。
注意
(1)寫操作fwrite()后必須關(guān)閉流fclose()。
(2)不關(guān)閉流的情況下,每次讀或?qū)憯?shù)據(jù)后,文件指針都會(huì)指向下一個(gè)待寫或者讀數(shù)據(jù)位置的指針。
讀寫常用類型
(1)寫int數(shù)據(jù)到文件
#include <stdio.h> #include <stdlib.h> int main () { FILE * pFile; int buffer[] = {1, 2, 3, 4}; if((pFile = fopen ("myfile.txt", "wb"))==NULL) { printf("cant open the file"); exit(0); } //可以寫多個(gè)連續(xù)的數(shù)據(jù)(這里一次寫4個(gè)) fwrite (buffer , sizeof(int), 4, pFile); fclose (pFile); return 0; }
(2)讀取int數(shù)據(jù)
#include <stdio.h> #include <stdlib.h> int main () { FILE * fp; int buffer[4]; if((fp=fopen("myfile.txt","rb"))==NULL) { printf("cant open the file"); exit(0); } if(fread(buffer,sizeof(int),4,fp)!=4) //可以一次讀取 { printf("file read errorn"); exit(0); } for(int i=0;i<4;i++) printf("%dn",buffer[i]); return 0; }
執(zhí)行結(jié)果:
5.讀寫結(jié)構(gòu)體數(shù)據(jù)
(1)寫結(jié)構(gòu)體數(shù)據(jù)到文件
#include <stdio.h> #include <string.h> #include <stdlib.h> typedef struct{ int age; char name[30]; }people; int main () { FILE * pFile; int i; people per[3]; per[0].age=20;strcpy(per[0].name,"li"); per[1].age=18;strcpy(per[1].name,"wang"); per[2].age=21;strcpy(per[2].name,"zhang"); if((pFile = fopen ("myfile.txt", "wb"))==NULL) { printf("cant open the file"); exit(0); } for(i=0;i<3;i++) { if(fwrite(&per[i],sizeof(people),1,pFile)!=1) printf("file write errorn"); } fclose (pFile); return 0; }
(2)讀結(jié)構(gòu)體數(shù)據(jù)
#include <stdio.h> #include <string.h> #include <stdlib.h> typedef struct{ int age; char name[30]; }people; int main () { FILE * fp; people per; if((fp=fopen("myfile.txt","rb"))==NULL) { printf("cant open the file"); exit(0); } while(fread(&per,sizeof(people),1,fp)==1) //如果讀到數(shù)據(jù),就顯示;否則退出 { printf("%d %sn",per.age,per.name); } return 0; }
執(zhí)行結(jié)果: