How to fread () structs?

struct book
{
    unsigned short  size_of_content;
    unsigned short  price;
    unsigned char  *content;
};

Suppose I have a file containing several books, each of which has a different size_of_content, priceand content. How can I read them at a time bookand determine which book (for example, price)?

size_t nread2;
struct book *buff = malloc(sizeof(struct book));
while( (nread2 = fread(buff, sizeof(struct book), 1, infp)) > 0 )
{
    printf("read a struct once \n");
}

This is what I still have. I tried to print whenever I read the structure. However, when I tried the input file with 5 structures, it will print 15 times ...

Thanks.

+4
source share
1 answer

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

, , , , .

+7

Source: https://habr.com/ru/post/1526490/


All Articles