Look at your own structand think about how big it is.
struct book {
unsigned short size_of_content;
unsigned short price;
unsigned char *content;
};
- unsigned short, , sizeof(unsigned short), , 2, 2 . .
. , unsigned char... . size_of_content... , size_of_content, price, .
, :
fread(&size_of_content, sizeof(size_of_content), 1, infp)
sanity-check the value of size_of_content and handle any error
fread(&price, sizeof(price), 1, infp)
sanity-check teh value of price and handle any error
buff->content = malloc(size_of_content)
check for error on malloc and handle any error
fread(buff->content, size_of_content, 1, infp)
, , , - , , , , ! .
struct , fread() . , , struct:
struct book_header {
unsigned short size_of_content;
unsigned short price;
};
struct book {
struct book_header header;
unsigned char *content;
}
fread() sizeof(book_header), . , , , .
, , , , " " "" .
http://en.wikipedia.org/wiki/Endianness
, . (-endian big-endian), C, , . , htonl() ntohl() .
http://linux.die.net/man/3/htonl
, , , , .