如何將struct array寫入文字檔? 如何從文字檔讀出struct array? (C/C++) (C)

Abstract
本文介紹如何將struct array寫入binary file,並從binary file讀出struct array。

Introduction

C語言 / fwrite_fread_struct_array.c

 1  /*  
 2  (C) OOMusou 2008  http://oomusou.cnblogs.com
 3 
 4  Filename    : fwrite_fread_struct_array.c
 5  Compiler    : Visual C++ 8.0
 6  Description : Demo how to fread / fwrite struct array to binary file
 7  Release     : 04/23/2008 1.0
 8  */
 9 
10  #include  < stdio.h >
11  #include  < string .h >
12 
13  #define  NAME_LEN 11
14  #define  ARRAY_SIZE 3
15 
16  struct  Student {
17     int   id;
18     char  name[NAME_LEN];
19  };
20 
21  typedef  struct  Student Student;
22 
23  int  main() {
24    Student student0[ARRAY_SIZE];  //  struct array for write
25    Student student1[ARRAY_SIZE];  //  struct array for read
26    FILE  * fp;                      //  file handle
27     int  i;                         //  for loop counter
28    
29     //  input struct array
30    student0[ 0 ].id  =   1 ;
31    strcpy(student0[ 0 ].name,  " clare " );
32    
33    student0[ 1 ].id  =   2 ;
34    strcpy(student0[ 1 ].name,  " jingyi " );
35    
36    student0[ 2 ].id  =   3 ;
37    strcpy(student0[ 2 ].name,  " jessie " );
38    
39     //  open binary file [write binary]
40     if  ( ! (fp  =  fopen( " library.dat " " wb " )))
41       return   - 1 ;
42    
43     //  size_t fwrite(const void *buf, size_t size, size_t n, FILE *fp)  
44    fwrite( student0,  sizeof (Student), ARRAY_SIZE, fp);
45    fclose(fp);  //  close file
46    
47     //  open binary file [read binary]
48     if  ( ! (fp  =  fopen( " library.dat " " rb " )))
49       return   - 1 ;
50    
51     //  size_t fread(void *ptr, size_t, size_t n, FILE *fp)
52    fread( student1,  sizeof (Student), ARRAY_SIZE, fp);
53     for (i  =   0 ; i  !=  ARRAY_SIZE;  ++ i) {
54      printf( " %d\n " , student1[i].id);
55      printf( " %s\n " , student1[i].name);
56    }
57      
58    fclose(fp);
59  }


執行結果

1
clare
2
jingyi
3
jessie


關鍵在於fwrite()和fread()兩個函數的用法:

size_t fwrite( const   void   * buf, size_t size, size_t n, FILE  * fp)  

size_t fread( void   * ptr, size_t, size_t n, FILE  * fp)


第一個參數傳的是要讀出或要寫入的起始位址,照理應該填入&student[0],因為array_name = &array_name[0],所以傳入陣列名稱即可。

第二個參數為每一個寫入/讀出資料的大小,由於一次寫入/讀取一個struct,所以為sizeof(struct Student)或sizeof(Student)。

第三個參數為寫入/讀出的數目,故傳入array size。

第四個參數為文字檔的file handler。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值