1

I have the following struct:

struct entry
{
    int next;
    int EOC;
} entry;

After creating an instance of the struct and setting its 'next' and 'EOC' values accordingly, I wrote the struct to a file via the C fwrite function. I'd now like to read the values of 'next' and 'EOC' from that file. My question is this: how are these two int variables stored in memory? Once I call fseek to move the file pointer to the correct byte in the file, how many bytes do I read to get the value of 'next' or 'EOC'?

1 Answer 1

4

If the file is written on the same machine as you read it, then:

  • You write with fwrite(&entry, sizeof(entry), 1, fp).
  • You read with fread(&entry, sizeof(entry), 1, fp).

The size you write is the size of the structure; the size you read is the size of the structure. You test the return values; they'll be either 0 or 1 given what I wrote, and 0 indicates a problem and 1 success in this context.

If your file is open for reading and writing, after writing, you'd seek backwards by sizeof(entry) and then read.

If your file is written on a different (type of) machine, then you may have to worry about the difference in the sizes of the basic data types, and in the endianness of the two systems, and with more complex structures, you might have to worry about packing and alignment rules too. There are ways of dealing with these issues (and they're more complex than single fwrite() and fread() calls).

Sign up to request clarification or add additional context in comments.

1 Comment

If you were interoperating with your Grandads mainframe you might also worry about the layout of negative integers!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.