fwrite函数的一般调用形式是什么?
fwrite() 是C 語言標(biāo)準(zhǔn)庫中的一個文件處理函數(shù),功能是向指定的文件中寫入若干數(shù)據(jù)塊,如成功執(zhí)行則返回實際寫入的數(shù)據(jù)塊數(shù)目。該函數(shù)以二進(jìn)制形式對文件進(jìn)行操作,不局限于文本文件。
語法:
fwrite(buffer,size,count,fp)
參數(shù):
buffer是準(zhǔn)備輸出的數(shù)據(jù)塊的起始地址
size是每個數(shù)據(jù)塊的字節(jié)數(shù)
count用來指定每寫一次或輸出的數(shù)據(jù)塊
fp為文件指針。
函數(shù)返回寫入數(shù)據(jù)的個數(shù)。
注意
(1)寫操作fwrite()后必須關(guān)閉流fclose()。
(2)不關(guān)閉流的情況下,每次讀或?qū)憯?shù)據(jù)后,文件指針都會指向下一個待寫或者讀數(shù)據(jù)位置的指針。
讀寫常用類型
(1)寫int數(shù)據(jù)到文件
#include?
#include?
int main ()
{
??FILE * pFile;
??int buffer[] = {1, 2, 3, 4};
??if((pFile = fopen ("myfile.txt", "wb"))==NULL)
??{
??????printf("cant open the file");
??????exit(0);
??}
??//可以寫多個連續(xù)的數(shù)據(jù)(這里一次寫4個)
??fwrite (buffer , sizeof(int), 4, pFile);
??fclose (pFile);
??return 0;
}
(2)讀取int數(shù)據(jù)
#include?
#include?
?
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 error\n");
????????exit(0);
????}
?
????for(int i=0;i<4;i )
????????printf("%d\n",buffer[i]);
????return 0;
}
執(zhí)行結(jié)果:
5.讀寫結(jié)構(gòu)體數(shù)據(jù)
(1)寫結(jié)構(gòu)體數(shù)據(jù)到文件
#include?
#include?
#include?
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 error\n");
????}
????fclose (pFile);
????return 0;
}
(2)讀結(jié)構(gòu)體數(shù)據(jù)
#include?
#include?
#include?
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 %s\n",per.age,per.name);
????}
????return 0;
}
執(zhí)行結(jié)果:
聲明:
本文于網(wǎng)絡(luò)整理,版權(quán)歸原作者所有,如來源信息有誤或侵犯權(quán)益,請聯(lián)系我們刪除或授權(quán)事宜。
總結(jié)
以上是生活随笔為你收集整理的fwrite函数的一般调用形式是什么?的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 全民k歌电脑怎么上传伴奏(全民K歌怎么上
- 下一篇: 设置mmi(设置mm在桌面打开游戏)