Reputation: 63
I have to write a structure to a file so i can read it in later. The struct is:
struct prog{
char* title;
char* channel;
struct tm* start;
struct tm* end;
float review;
enum soort sort;
union type *type;
};
union type{
struct serie *ep;
struct film *mov;
};
struct serie{
int seznum;
int epnum;
char* eptitle;
};
struct film{
char* reg;
char* act;
char* genre;
};
enum sort { film, serie }
So you can see that there are pointers to strings and the struct tm (from time.h). I can't figure out how to write it to a binary file, all i can do is write it string by string but there must be a more efficient way to write the previous struct. I think the problem starts with the char* and the pointers to the tm structs because the program is now going to write the adress of the start of a string or the adress of the tm struct. I wan't to write the string and not the adress to a file. I tried with record I/O but it writes the adresses so i can't read them later. Thanks!
Upvotes: 1
Views: 1653
Reputation: 31669
You may want to look at time_t or other alternatives which can store time in a single integer timestamp. You can also use a database or a simple file storage class.
Otherwise you can't really improve this with native C functions. You could remove pointers and use fixed character arrays like so:
struct T_film
{
char text[50];
int i;
};
struct T_prog
{
char title[50];
tm start;
tm end;
T_film film;
};
T_prog data;//initialize...
fwrite(&data, 1, sizeof(T_prog), fout);
fseek(fin,0,0);
fread(&data, 1, sizeof(T_prog), fin);
Now the structure has a fixed pattern and everything can be stored in binary. BUT, this can be even more inefficient. The size of text is too short, or too long with extra blank space which takes too long to read. It's not portable either. So you may want to stick to pointers and reading/writing with makeshift methods.
You can also separate fixed sized data and put them in a separate structure. Write the fixed sized data in one block, then write the character strings one by one.
Upvotes: 1