Reputation: 35
I have a program with menu. Struct is called "Siunta", struct with new values called "nauja". I'm trying to write it to file and then read from file. Functions for reading and writing are provided below. The error message in compiler:
|144|error: 'Siunta' undeclared (first use in this function)|.
What could be wrong?
writing :
FILE* fp = fopen("file.bin", "wb");
struct Siunta nauja;
fwrite(&(nauja.siuntos_nr), sizeof(nauja.siuntos_nr), 1, fp);
fwrite(&(nauja.destination), sizeof(nauja.destination), 1, fp);
fwrite(&(nauja.svoris), sizeof(nauja.svoris), 1, fp);
fclose(fp);
reading :
FILE* fp = fopen("file.bin", "rb");
struct Siunta nauja2;
fread(&nauja2, sizeof(Siunta),1,fp);
printf("siuntos nr: %d destination: %s Svoris: %d",nauja2.siuntos_nr, nauja2.destination, nauja2.svoris);
Upvotes: 2
Views: 134
Reputation: 2096
The error that occurs is due to the sizeof(Siunta) that may be sizeof(struct Siunta), but you may use also sizeof(nauja2) (that might be better).
Reading your code, I see you have written some fields of the structure Siunta, but after you want read all the structure!
You have to write the structure using:
fwrite(&nauja, sizeof(nauja), 1, fp);
Then you may read:
fread(&nauja2, sizeof(nauja2), 1, fp);
Upvotes: 3
Reputation: 59987
Just write the structure field by field. Also use network ordering for numbers. This will make it future proof along with putting a version number at the start.
Upvotes: 0
Reputation: 7320
You need to write struct Siunta
instead of Siunta
in:
fread(&nauja2, sizeof(Siunta),1,fp);
Or, you can create a typedef beforehand, like this:
typedef struct Siunta Siunta;
Upvotes: 2