Using fread to read the contents of a file into a structure

The book "Advanced Programming in Unix" contains a part (ch 8.14, p. 251) in which the author shows us the definition of the structure "acct" (used to store account information). Then it shows a program in which it reads accounting data from a file into a structure (the key part of which):

fread (&acdata, sizeof(acdata), 1, fp)

The problem I ran into is that I heard that C compilers sometimes reorder structure elements in memory to make better use of space (due to alignment problems). Thus, if this code simply takes the entire contents of the file and inserts it into acdata (and the contents of the file are ordered according to the order specified in the structure definition), if some elements of the structure were moved, then if I access them in the code, I I probably won’t get what was expected (since the data in the file was not reordered the way the structure did in memory).

What am I missing (because from what I get, it doesn't seem reliable)?

Thank you for your help (my apologies if I did something wrong procedurally - this is my first post)

+3
source share
4 answers

Yes

Your program will be stable.

Your question has touched the bonfire of portability recommendations that you really did not ask for. The question you seemed to ask was, "is this code and my program stable?" And the answer is yes.

The structure will not be reordered. C99 specifically prohibits reordering of structural elements. 1

In addition, the location and alignment are independent of the level of optimization. If they did, all programs would have to be completely built with the same level of optimization, as well as with all library programs, the kernel, all kernel interfaces, etc.

, - .

ABI. . , , . ( , , . , , . .) , .

, , . . , , :

  • . ( , ) , , memcpy (3). .
  • . , YAML , , XML, , , . , . , , , C ++.

Paxdiablo, , , , , , . . , .


1. C99 6.7.2.1 (13) , - , , .

+2

Worry!

, . , , , - - , , , , ; ; , fwrite( ) fread( ). 1- , . - .

(), ; , .

. . .

, , , . , . . , , , whiz-bang x86-64 , 32- .

: .

, . .

, , . , C.

+8

( , ) , .

- : -)

, ( , , ), , , .

C99:

6.2.6.1/1: , .

6.2.6.1/6 ( ): , -, , . , .

. , , ( , ).

6.7.2.1/13:... , .

6.7.2.1/15: .


1.1 , ( , , #pragma pack ..), , ( ).

"" 1.1, . ( , ) .

, 16- , , , , , ( - ).

- - , , , , .

+3

, . . .

+2

All Articles