Pregunta

struct FATEntry entry1;
    strcpy(entry1.name, "abc");
    entry1.next = 3;
    entry1.size = 10;
    entry1.mtime = 100;

    struct FATEntry entry2;
    strcpy(entry1.name, "");
    entry1.next = 0;
    entry1.size = 0;
    entry1.mtime = 0;

    struct FATEntry entry3;
    strcpy(entry1.name, "foo");
    entry1.next = 324;
    entry1.size = 3;
    entry1.mtime = 434;

    file1 = fopen("filesys", "r+b");
    fwrite(&entry1, sizeof(struct FATEntry), 1, file1);


    fseek(file1,BLOCK_SIZE,SEEK_SET);


    fwrite(&entry3, sizeof(struct FATEntry), 1, file1);

fseek(file1,BLOCK_SIZE,SEEK_SET);


    fread(&entry2, sizeof(struct FATEntry), 1, file1);
    fclose(file1);

So basically what I am trying to do here is write entry1 to the file then seek 512 bytes (since that will be a block) and then write entry3 to the file. But when I fread I'm supposed to be getting the values from entry3 but into entry2 but all I see in entry2 are random numbers. What am I doing wrong?

¿Fue útil?

Solución

First thing you need to do is check the return values from fopen, fwrite, fread, fseek, etc. You will start seeing errors that you are missing.

One thing you need to understand is that fseek will not seek past the end-of-file. Thus, if you are starting with an empty file and fwrite 40 bytes, then fseek to 512, then fwrite another 40 bytes, the second write will actually start at byte 80, not 512! You then fseek to 512, ending up at EOF at 80 and try to fread 40 bytes. You will actually read 0 bytes as you are at EOF and your read buffer will contain whatever it had previously (uninitialized memory?).

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top