文件操作:fread()和fwrite()
生活随笔
收集整理的這篇文章主要介紹了
文件操作:fread()和fwrite()
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
fread和fwrite函數功能 ? ? 用來讀寫一個數據塊。 ? 一般調用形式 ? ? fread(buffer,size,count,fp); ? ? fwrite(buffer,size,count,fp); ? 說明 ? ? (1)buffer:是一個指針,對fread來說,它是讀入數據的存放地址。對fwrite來說,是要輸出數據的地址。 ? ? (2)size:要讀寫的字節數; ? ? (3)count:要進行讀寫多少個size字節的數據項; ? ? (4)fp:文件型指針。 ? 注意:1 完成次寫操(fwrite())作后必須關閉流(fclose()); ? ? ? ? ? ? ?2 完成一次讀操作(fread())后,如果沒有關閉流(fclose()),則指針(FILE * fp)自動向后移動前一次讀寫的長度,不關閉流繼續下一次讀操作則接著上次的輸出繼續輸出; ? ? ? ? ? ? ?3 fprintf() : 按格式輸入到流,其原型是int fprintf(FILE *stream, const char *format[, argument, ...]);其用法和printf()相同,不過不是寫到控制臺,而是寫到流罷了。注意的是返回值為此次操作寫入到文件的字節數。如int c = fprintf(fp, "%s %s %d %f", str1,str2, a, b) ;str1:10字節;str2: 10字節;a:2字節;b:8字節,c為33,因為寫入時不同的數據間自動加入一個空格。 ? 文件使用之后一定要關閉,否則將不能正確顯示內容.fwrite:讀入兩個學生信息然后用fwrite存入文件 ? fread:用fread從文件中讀出學生信息。 ? 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"); } }
轉載于:https://www.cnblogs.com/yedushusheng/p/4333839.html
總結
以上是生活随笔為你收集整理的文件操作:fread()和fwrite()的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android开发:1-3、Androi
- 下一篇: 操作系统之内存管理:2、内存管理的功能(