Writing/reading array of structures to file

Can anyone tell me if there is a straightforward way of doing this please?
I have an array of objects, for which an object class has been declared. My program moves objects (numbers) between array locations and I would like to be able to suspend operations by saving to a file and at a later date, reinitialising from the file so that it can resume where it left off.

For writing to file, this occurred to me first:
for(x = 0; x < NUMBER; x++)
{
fprintf(<file pointer>,"%d\t %d\t %d\n",array[x].a, array[x].b, array[x].c);
}

No doubt this would give me nicely formatted columns of numbers in the file, but I cannot see there being a command that does the inverse. I looked through "Teach yourself C programming in 21 days" by Aitken & Jones, where I found fwrite() and fread(), but cannot see how they can be applied to this problem.

Is there a straightforward way of doing this please? Or do I have to:
Convert individual numbers in a class into characters then cancatenate into a string for writing to file.
Then for reading back, read a line, split it into seperate sub-strings and then convert each back into its number? Doing it this way sounds rather laborious.
Thanks.
If you just need something quick and dirty and you want to write a simple struct/class that contains no virtual functions
and contains only simple POD types (fundamental types such as int, float, char, bool, etc.), then use fread and fwrite:

1
2
3
4
5
6
7
8
9
10
struct MyStruct {
    int x;
    char y;
    float z;
};

MyStruct s; // assume it is filled out
FILE* fp;    // assume file is open for writing
if( fwrite( &s, sizeof( s ), 1, fp ) != 1 )
    std::cout << "PANIC: failed to write data!" << std::endl;


I have never tried to do stuff with stdio.h, but from a quick glance at the c++ reference on this site, it seems that you need fscanf. http://www.cplusplus.com/reference/clibrary/cstdio/fscanf/
Topic archived. No new replies allowed.