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'?
If the file is written on the same machine as you read it, then:
fwrite(&entry, sizeof(entry), 1, fp)
.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).