新聞中心
fwrite和fread是以記錄為單位的I/O函數(shù),fread和fwrite函數(shù)一般用于二進(jìn)制文件的輸入輸出。

創(chuàng)新互聯(lián)公司成立于2013年,是專業(yè)互聯(lián)網(wǎng)技術(shù)服務(wù)公司,擁有項(xiàng)目成都做網(wǎng)站、網(wǎng)站制作網(wǎng)站策劃,項(xiàng)目實(shí)施與項(xiàng)目整合能力。我們以讓每一個(gè)夢(mèng)想脫穎而出為使命,1280元大豐做網(wǎng)站,已為上家服務(wù),為大豐各地企業(yè)和個(gè)人服務(wù),聯(lián)系電話:028-86922220
1.函數(shù)功能
用來讀寫一個(gè)數(shù)據(jù)塊。
2.一般調(diào)用形式
- fread(buffer,size,count,fp);
- fwrite(buffer,size,count,fp);
3.說明
(1)buffer:是一個(gè)指針,對(duì)fread來說,它是讀入數(shù)據(jù)的存放地址。對(duì)fwrite來說,是要輸出數(shù)據(jù)的地址。
(2)size:要讀寫的字節(jié)數(shù);
(3)count:要進(jìn)行讀寫多少個(gè)size字節(jié)的數(shù)據(jù)項(xiàng);
(4)fp:文件型指針。
注意:1 完成次寫操(fwrite())作后必須關(guān)閉流(fclose());
2 完成一次讀操作(fread())后,如果沒有關(guān)閉流(fclose()),則指針(FILE * fp)自動(dòng)向后移動(dòng)前一次讀寫的長(zhǎng)度,不關(guān)閉流繼續(xù)下一次讀操作則接著上次的輸出繼續(xù)輸出;
3 fprintf() : 按格式輸入到流,其原型是int fprintf(FILE *stream, const char *format[, argument, ...]);其用法和printf()相同,不過不是寫到控制臺(tái),而是寫到流罷了。注意的是返回值為此次操作寫入到文件的字節(jié)數(shù)。
如:
- int c = fprintf(fp, "%s %s %d %f", str1,str2, a, b) ;
str1:10字節(jié);str2: 10字節(jié);a:2字節(jié);b:8字節(jié),c為33,因?yàn)閷懭霑r(shí)不同的數(shù)據(jù)間自動(dòng)加入一個(gè)空格。
文件使用之后一定要關(guān)閉,否則將不能正確顯示內(nèi)容.fwrite:讀入兩個(gè)學(xué)生信息然后用fwrite存入文件
fread:用fread從文件中讀出學(xué)生信息。
fwrite.c
- #include
- #define SIZE 2
- struct student_type
- {
- char name[10];
- int num;
- int age;
- char addr[10];
- }stud[SIZE];
- void save()
- {
- FILE *fp;
- int i;
- if((fp=fopen("stu_list","wb"))==NULL)
- {
- printf("cant open the file");
- exit(0);
- }
- for(i=0;i
- {
- if(fwrite(&stud[i],sizeof(struct student_type),1,fp)!=1)
- printf("file write error\n");
- }
- fclose(fp);
- }
- main()
- {
- int i;
- for(i=0;i
- {
- scanf("%s%d%d%s",&stud[i].name,&stud[i].num,&stud[i].age,&stud[i].addr);
- save();
- }
- for(i=0;i
- {
- printf("%s,%d,%d",stud[i].name,stud[i].num,stud[i].age,stud[i].addr);
- }
- }
fread.c
- #include
- #define SIZE 2
- struct student_type
- {
- char name[10];
- int num;
- int age;
- char addr[10];
- }stud[SIZE];
- void read()
- {
- FILE *fp;
- int i;
- if((fp=fopen("stu_list","rb"))==NULL)
- {
- printf("cant open the file");
- exit(0);
- }
- for(i=0;i
- {
- if(fread(&stud[i],sizeof(struct student_type),1,fp)!=1)
- printf("file write error\n");
- }
- fclose(fp);
- }
- main()
- {
- int i;
- read();
- for(i=0;i
- {
- printf("%s,%d,%d,%s",stud[i].name,stud[i].num,stud[i].age,stud[i].addr);
- printf("\n");
- }
- }
希望對(duì)你有幫助。
【編輯推薦】
- C++必須明白的基礎(chǔ)20條
- C++多態(tài)技術(shù)的實(shí)現(xiàn)和反思
- VC++如何將程序最小化到托盤
- C/C++中內(nèi)存區(qū)域劃分大總結(jié)
- 階乘相關(guān)的算法及其C++實(shí)現(xiàn)
當(dāng)前題目:介紹C/C++文件的操作函數(shù)
分享網(wǎng)址:http://www.dlmjj.cn/article/dpjesoj.html


咨詢
建站咨詢
