fread函数和fwrite函数

  • 格式:pdf
  • 大小:76.54 KB
  • 文档页数:4

3. 说 明
( 1 ) bu f f e r : 是 一 个 指 针 , 对 fr e a d 来 说 , 它 是 读 入 数 据 的 存 放 地 址 。 对 fw r i t e 来 说 , 是 要 输 出 数 据 的 地 址 。 ( 2 ) si z e : 要 读 写 的 字 节 数 ;
( 3 ) co u n t : 要 进 行 读 写 多 少 个 s i z e 字 节 的 数 据 项 ;
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"); } }
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); }
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,&am ) fp : 文 件 型 指 针 。 注意:1 完成次写操(fwrite())作后必须关闭流(fclose()); 2 完成一次读操作(fread())后,如果没有关闭流 (fclose()),则指针(FILE * fp)自动向后移 动前一次读写的长度,不关闭流继续下一次读操作则接着上次的输出继续输出; 3fprintf() : 按格式输入到流,其原型是 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 从文件中读出学生信息。
1. 函 数 功 能
用 来读 写 一个 数 据块 。
2. 一 般 调 用 形 式
fr e a d ( b u f f e r , s i z e , c o u n t , f p ) ;
fw r i t e ( b u f f e r , s i z e , c o u n t , f p ) ;