Abstract
This article describes how to merge a struct array into binary file and export a struct array from binary file.
Introduction
C statement/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 }
Results
1
Clare
2
Jingyi
3
Jessie
Usage of fwrite () and fread () functions:
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)
The first parameter indicates the starting address to be exported or imported. It should be set to & Student [0], because array_name = & array_name [0], therefore, you only need to enter the region column name.
The second parameter indicates the size of each incoming/outgoing resource. The result is that a struct is obtained at One inbound/outbound operation, so sizeof (struct student) or sizeof (student ).
The Third Metric is the inbound/outbound metric, so the array size is used.
The fourth example is the file handler of the text handler.
See also
(Original) how to insert struct into vector? (C/C ++) (STL)