代码示例_标准IO_fread / fwrite

fread_fwrite


 fread_fwrite.c

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <string.h>
 4 
 5 typedef struct info{
 6     int age;
 7     int tail;
 8     char name[20];
 9 }info;
10 
11 
12 int main(void)
13 {
14     info panda = {20,180,"panda_w"};
15 
16     // 打开/创建
17     FILE *fp = fopen("./1.text","w+");
18     if(fp==NULL){
19         perror("fopen failed");
20         exit(1);
21     }
22 
23     //
24     if(  fwrite(&panda,sizeof(info),1,fp)==1  )
25         printf("write OK!
");
26 
27     // 关闭
28     fclose(fp);
29 
30 
31     // 打开/创建
32     fp = fopen("./1.text","r");
33     if(fp==NULL){
34         perror("fopen failed");
35         exit(1);
36     }
37 
38     //
39     info pa ;
40 
41     if(  fread(&pa,sizeof(pa),1,fp)==1  )
42         printf("read success!
");
43 
44     printf("age:%d
tail:%d
name:%s
",pa.age,pa.tail,pa.name);
45 
46 
47     return 0 ;
48 }

测试:


success !

Stay hungry, stay foolish 待续。。。
原文地址:https://www.cnblogs.com/panda-w/p/11075731.html