2

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;
}
2
  • It's enough to fread(curr) and not fread(&curr). Also be careful with the pointers, as next will be compromised after writing it and reading it back.
    – foxx1337
    Nov 28, 2012 at 9:15
  • @foxx1337: curr is a wild pointer, so although you're right about removing the dereference, it's still not going to work.
    – Paul R
    Nov 28, 2012 at 9:24

4 Answers 4

3

curr is an uninitialised pointer (a FLUG*) and is therefore not pointing to valid memory when fread() is called. Writing to invalid memory is undefined behaviour (the program could seg fault or execute incorrectly or worst case execute correctly). Either create a stack allocated object (of type FLUG) or dynamically allocate memory for curr.

Personally, I find it very confusing when a pointer is typedefd as at the point of use it is not obvious that the variable is a pointer:

ELEM_ZGR curr;

The following is unambiguous:

FLUG* curr; /* Or just 'FLUG curr;' for this case. */

Check the result of fread() to ensure the program is not operating on stale data:

FLUG curr;
while (1 == fread((&curr, sizeof(FLUG), 1, fp))
{
    printf("\n%d", curr.flugnummer);
}

(In response to the question edit)

In short, change:

fwrite(curr, sizeof(FLUG*), 1, fp);
fread(&curr, sizeof(FLUG*), 1, fp);

to:

fwrite(curr, sizeof(FLUG), 1, fp);
fread(curr, sizeof(FLUG), 1, fp);

In both cases, curr is a FLUG* and is pointing to valid memory for storing a FLUG so you need to read the sizeof(FLUG), not the sizeof(FLUG*). The typical size for a pointer of any type is 4 or 8 bytes. On my x86 box it is 4 bytes and the size of a FLUG is 88 bytes. The size argument to both fwrite() and fread() instructs the number of bytes to read and write:

fwrite(curr, sizeof(FLUG), 1, fp); /* write 88 bytes to fp from address curr. */
fread(curr, sizeof(FLUG), 1, fp); /* read 88 bytes from fp and write to the
                                     address beginning at curr. */

Passing the address of &curr to fread() means a FLUG** is being passed to fread() which is incorrect.

5
  • But how do I get the FLUG struct into the pointer and the other way around? Is that even possible?
    – OhSnap
    Nov 28, 2012 at 9:28
  • @user854699, I don't understand what you mean.
    – hmjd
    Nov 28, 2012 at 9:30
  • I have a pointer which I use to go through the list. As you guys said I can't put these pointers into the file. I need to put in the structs, but how do I convert the pointers to structs?
    – OhSnap
    Nov 28, 2012 at 9:36
  • @user854699, when writing to the file you need to pass the address of the struct to fwrite(). A pointer holds the address of a variable (commonly stated as points to). In your case, a FLUG* holds the address of a FLUG. When calling fwrite() you pass in a FLUG*, the address of a FLUG.
    – hmjd
    Nov 28, 2012 at 9:38
  • That apparently doesn't work. I get the error "Debug Assertion Failed!". Thanks for the information, though. Now I'm a little less stupid concerning this stuff. Still don't knof why it won't work though.
    – OhSnap
    Nov 28, 2012 at 12:00
2

Whoa! Think what memory you're reading into there. Your fread is asking for data to get dumped in some random location (because curr is uninitialised, so points to memory that probably doesn't exist in your process). You need to allocate some FLUGs and read into them.

Another problem is that you shouldn't be writing pointers to file; the data only has meaning within your process. When you read back the FLUGs, at the very least, you should set cur->next to something sensible (like the next FLUG!).

2

In the read routine ELEM_ZGR curr; is just an uninitialised pointer. You need to do something like this:

void fluege_laden() {
    FLUG curr;  // <<<- allocate an actual struct here rather than just a pointer
    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);
    }
}

Also, in the write routine you need to write the whole struct, e.g.

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); // <<<- curr is already a pointer - do not dereference here !
    }

    fclose(fp);
    return 1;
}
0

You are writing pointers to a file, called a shallow copy. Pointers are not transferable, you need to write code to do a deep copy. Either that, or use something like JSON or YAML.

5
  • Uhm .. I'll take the deep copy way, but I don't know how to do this. How do I convert the values from the pointer to the struct?
    – OhSnap
    Nov 28, 2012 at 9:31
  • You need to allocate a memory buffer for each value and copy them specifically, then write the buffer. Obviously you will need a structure to your file to be able to identify each component. When reading back-in you need to read each value back in to a prepared memory area, so you might need to store the size of each component as well. A lot of work! JSON and YAML do all that for you, but as text (so they can be slow).
    – cdarke
    Nov 28, 2012 at 11:03
  • I can't do that as this is sort of a thing I have to do for college. Is there no way to save this data without the use of extern sources?
    – OhSnap
    Nov 28, 2012 at 11:48
  • If you can use an external sorce then you have to write it yourself! Welcome to C.
    – cdarke
    Nov 28, 2012 at 11:56
  • I can't imagine that it is that difficult. This is a exercise for basic course for C.
    – OhSnap
    Nov 28, 2012 at 12:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.