Daniel Jakobsen Hallel
Daniel Jakobsen Hallel

Reputation: 584

how to read from binary file into struct c?

i have the following struct

struct
{
    char order;
    int row;
    int column;
    int length;
    char printChar;
}record;

and my file look's like this

F
30
40
7
X

how can i use fread to store the file in the struct? does my file appear correctly or should all the components need to be in one-line?

Upvotes: 1

Views: 12094

Answers (3)

effeffe
effeffe

Reputation: 2881

Your file seems to be a text file, so if that's exactly the format of the file, you can use fscanf:

fscanf(file, "%c%d%d%d%c", &(record.order), &(record.row), ...

You can check the return value if you're interested in basic error handling. If you need a better description of the error, just use fgets to read one line at a time and parse it with sscanf, atoi, strtol and similar functions.

If you want to directly save data in the structure, no, you can't (with that kind of file), in a text file 30 is a string of two characters, not an integer in binary form.

Upvotes: 0

user529758
user529758

Reputation:

If I understand correctly, you're asking if you can do

struct record r;
fread(file, &r, sizeof(r));

or are you forced to use

struct record r;
fread(file, &r.order, sizeof(r.order));

If this is your question, then the answer is: you have to read the fields one-by-one since there may be padding between struct members. Or, if you use a GNU-compatible compiler, you might instruct it not to include any padding by declaring your struct as "packed":

struct record {
    // ...
} __attribute__((packed));

But this is not advised unless absolutely necessary (it's not portable).

Also, is your file really a binary file? If not, you should pay attention to newline characters and converting the numbers from text to their actual numeric value.

Upvotes: 8

Mark Wilkins
Mark Wilkins

Reputation: 41222

It is not possible to read from a file in that format (essentially containing the character representations of the data) into the structure. One method for reading it would be to use fgets and read each line and assign the data into the structure (converting numeric values as necessary with functions such as strtol or perhaps atoi if error checking is not as important).

Upvotes: 1

Related Questions