I'm currently trying to write and read a simple linked list into a file, but it doesn't really seem to work and I'm not sure if it is even possible.
typedef struct flug
{
int flugnummer;
char flugziel[50];
enum TAG flugtag;
int flugzeit_stunde;
int flugzeit_minute;
int gateway;
char status[10];
struct flug *next;
}FLUG;
typedef FLUG *ELEM_ZGR;
I fear the problem might be that I'm not only writing chars, but int .. and especially enums, too.
int fluege_sichern() {
ELEM_ZGR curr;
FILE *fp;
char* tag;
curr = first;
if (fopen_s(&fp, datei,"a+b") != 0) {
printf("\nDatei %s nicht zum Anhaengen zu oeffnen",datei);
PAUSE;
exit(1);
}
for(curr = first; curr != NULL; curr = curr->next) {
fwrite(curr, sizeof(FLUG), 1, fp);
}
fclose(fp);
return 1;
}
This is supposed to be the function to write the elements into a file as binaries. I don't get any errors in this function.
void fluege_laden() {
ELEM_ZGR curr;
FILE *fp;
int i = 0;
if (fopen_s(&fp, datei,"rb") != 0) {
printf("\nDatei %s nicht zum Lesen zu oeffnen",datei);
PAUSE;
exit(1);
}
while(1) {
fread(&curr, sizeof(FLUG), 1, fp);
printf("\n%d", curr->flugnummer);
//fluege_sortieren(curr);
}
}
I get the error when I try to print out curr->flugnummer.
Ok so I changed the two functions a little, but it still doesn't seem to work. I'm sorry, I don't seem to get it...
[EDIT2] Another version that doesn't work:
void fluege_laden() {
ELEM_ZGR curr; // <<<- allocate an actual struct here rather than just a pointer
FILE *fp;
int i = 0;
curr = first;
if (fopen_s(&fp, datei,"rb") != 0) {
printf("\nDatei %s nicht zum Lesen zu oeffnen",datei);
PAUSE;
exit(1);
}
while(1) {
fread(curr, sizeof(FLUG), 1, fp);
printf("\n%d", curr->flugnummer); // <<<
printf("\n%s", curr->flugziel);
//fluege_sortieren(curr);
PAUSE;
}
}
int fluege_sichern() {
ELEM_ZGR curr;
FILE *fp;
curr = first;
if (fopen_s(&fp, datei,"a+b") != 0) {
printf("\nDatei %s nicht zum Anhaengen zu oeffnen",datei);
PAUSE;
exit(1);
}
for(curr = first; curr != NULL; curr = curr->next) {
fwrite(curr, sizeof(FLUG), 1, fp);
}
fclose(fp);
return 1;
}
fread(curr)
and notfread(&curr)
. Also be careful with the pointers, asnext
will be compromised after writing it and reading it back.curr
is a wild pointer, so although you're right about removing the dereference, it's still not going to work.