user2793162
user2793162

Reputation:

writing data structure to a file

I know following approach may not be portable but that is exactly what I want to find out now. Imagine I have some data structure

struct student
{
    char name[20];
    int age;
} x;

Now I want to write it to a file like this:

fwrite(&x, sizeof(student), 1, filePointer);

Read similarly:

fread(voidPointer, sizeof(student), 1, filePointer);
// Now possibly do a memcpy
memcpy(studentObjectPointer, voidPointer, sizeof(student));

My question is: Say I don't want to copy this file to another computer, and I will read it from the same computer that created this file. Will the portability (endianness, packed data structure) issues still apply to above approach? Or it will work fine?

Upvotes: 0

Views: 439

Answers (2)

ern0
ern0

Reputation: 3172

Remember, we're living in a 4-dimension world. You said, the saved file will not move in the x, y and z axis, it will be used on the same computer. But you did not mentioned the 4th dimension, the time. If the structure changes, it will fail.

At least, you should put a signature field in the structure. Fill it with a constant value before write(), check it right after read(), and change the constant value when the structure gets modified.

Upvotes: 0

Rerito
Rerito

Reputation: 6086

If the file would be copied on other machines, you will have to build your own serializer and deserializer. With the structure you gave it is quite simple.

You have to define which endianness to adopt when writing numbers (here, the int age). Here, you could process like this :

  1. Open the file in binary mode
  2. Write the 20 bytes of the name string
  3. Write the age in a CHOSEN endianness (big endian)

When reading it back, you will certainly have to convert the Big-Endianness to the local endianness of the machine.

There is still a remaining issue : if sizeof (int) is not the same between the two machines. In that case things get more vicious and I think the above is not sufficient. If you really need to be portable across a wide range of machines, consider the use of specific length types defined in #include <stdint.h> such as int32_t for instance.

Upvotes: 1

Related Questions