介紹C/C++文件的操作函數(shù)
fwrite和fread是以記錄為單位的I/O函數(shù),fread和fwrite函數(shù)一般用于二進(jìn)制文件的輸入輸出。
1.函數(shù)功能
用來(lái)讀寫(xiě)一個(gè)數(shù)據(jù)塊。
2.一般調(diào)用形式
- fread(buffer,size,count,fp);
- fwrite(buffer,size,count,fp);
3.說(shuō)明
(1)buffer:是一個(gè)指針,對(duì)fread來(lái)說(shuō),它是讀入數(shù)據(jù)的存放地址。對(duì)fwrite來(lái)說(shuō),是要輸出數(shù)據(jù)的地址。
(2)size:要讀寫(xiě)的字節(jié)數(shù);
(3)count:要進(jìn)行讀寫(xiě)多少個(gè)size字節(jié)的數(shù)據(jù)項(xiàng);
(4)fp:文件型指針。
注意:1 完成次寫(xiě)操(fwrite())作后必須關(guān)閉流(fclose());
2 完成一次讀操作(fread())后,如果沒(méi)有關(guān)閉流(fclose()),則指針(FILE * fp)自動(dòng)向后移動(dòng)前一次讀寫(xiě)的長(zhǎng)度,不關(guān)閉流繼續(xù)下一次讀操作則接著上次的輸出繼續(xù)輸出;
3 fprintf() : 按格式輸入到流,其原型是int fprintf(FILE *stream, const char *format[, argument, ...]);其用法和printf()相同,不過(guò)不是寫(xiě)到控制臺(tái),而是寫(xiě)到流罷了。注意的是返回值為此次操作寫(xiě)入到文件的字節(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)閷?xiě)入時(shí)不同的數(shù)據(jù)間自動(dòng)加入一個(gè)空格。
文件使用之后一定要關(guān)閉,否則將不能正確顯示內(nèi)容.fwrite:讀入兩個(gè)學(xué)生信息然后用fwrite存入文件
fread:用fread從文件中讀出學(xué)生信息。
fwrite.c
- #include <stdio.h>
- #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<SIZE;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<SIZE;i++)
- {
- scanf("%s%d%d%s",&stud[i].name,&stud[i].num,&stud[i].age,&stud[i].addr);
- save();
- }
- for(i=0;i<SIZE;i++)
- {
- printf("%s,%d,%d",stud[i].name,stud[i].num,stud[i].age,stud[i].addr);
- }
- }
fread.c
- #include <stdio.h>
- #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<SIZE;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<SIZE;i++)
- {
- printf("%s,%d,%d,%s",stud[i].name,stud[i].num,stud[i].age,stud[i].addr);
- printf("\n");
- }
- }
希望對(duì)你有幫助。
【編輯推薦】


















