TAGS :Viewed: 9 - Published at: a few seconds ago

[ read a binary file opened by fopen("ab") (add,binary) ]

I am just learning to work with FILEs. My problem is this: when I want to read a binary file that was opened by fopen("example.dat", "ab"), it shows something like:

this pic

But when I open file by fopen("example.dat", "wb"), it works!

Here are my test programs:

to write on file:

#include <stdio.h>
void main() {
    int i = 0;
    FILE *save = fopen("save.dat", "wb");
    char str[5][40];
    while (i < 5) {
        gets(str[i]);
        fwrite(str[i], sizeof(char), 40, save);     
        i++;
    }
}

to read:

#include <stdio.h>
void main() {
    char str2[100][400];
    int i = 0;
    FILE *load = fopen("save.dat", "rb");
    if (!load) {
        printf("cant open file!");
        return;
    }
    fread(str2[i], sizeof(char), 40, load);
    while (!feof(load)) {
        puts(str2[i]);
        printf("\n");
        i++;
        fread(str2[i], sizeof(char), 40, load);
    }
}

I need "ab" because it is about saving info of a game and it shouldn't delete after closing program or run it again .

and sorry for my English ;)

Answer 1


The most likely cause of your problem is opening the file with "ab" does not truncate it, therefore you are appending to the same file and keep reading whatever incorrect output was written there first.

In addition, your code has several problems:

  • Never use gets(). It was removed from the C Standard because it cannot be told how large the buffer is a therefore cannot be used safely.
  • Your test for end of file is incorrect: never use feof(), because it does not do what you think it does. It can only tell you if the end of file has been encountered by a stream function that actually tried to read past it. You can simply test the return value from fread.
  • The prototype for main is either int main(void) of int main(int argc, char *argv[])
  • You should check for correct boundaries to prevent reading past the end of the str2 array.

Here is a corrected version:

#include <stdio.h>

int main(void) {
    char str2[100][400];
    FILE *load = fopen("save.dat", "rb");
    if (!load) {
        printf("cant open file!\n");
        return 1;
    }
    for (int i = 0; i < 100 && fread(str2[i], sizeof(char), 40, load) == 40; i++) {
        puts(str2[i]);
        printf("\n");
    }
    fclose(load);
    return 0;
}