2

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 .

alizeyn
  • 2,300
  • 1
  • 20
  • 30
  • Use an editor that can display the binary contents. – Thomas Matthews Jan 21 '16 at 21:17
  • @user3121023 i tried it delete last saved data on file – alizeyn Jan 21 '16 at 21:23
  • heeyyyy whyy nagative votes!!! i am just a poor Engineer student – alizeyn Jan 21 '16 at 21:25
  • If I change the first program to use `"ab"` instead of `"wb"`, the second program will still read it properly. What exactly is the problem? You should post the code that is problematic, not the working code. – dbush Jan 21 '16 at 21:29
  • I can't see why this wouldn't work - it's not the best design, but it should at least work. – user253751 Jan 21 '16 at 21:30
  • You could also open it as `"rb+"` which is read, binary, append. You can then `fseek` and write into the file. – David Hoelzer Jan 21 '16 at 21:32
  • no, when you change it to "ab" you see some unwanted signs like picture before each string this the problem @dbush – alizeyn Jan 21 '16 at 21:34
  • You should learn why [`while(!feof)` is always wrong](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong). – molbdnilo Jan 21 '16 at 21:35
  • Not when I tested it. You need to post a [Minimal, Complete, Verifiable Example](http://stackoverflow.com/help/mcve) of the problem you're having. – dbush Jan 21 '16 at 21:35
  • @DavidHoelzer i see .but when you exit program and run it again "w" delete all the things that you saved on file instantly after open it so i should use "a" because i need last data – alizeyn Jan 21 '16 at 21:37
  • Or check if it exists and if it does, rb+. – David Hoelzer Jan 22 '16 at 03:58

1 Answers1

2

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;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
  • tnx for your correction and help it was so helpful, i tried your new code but it didn't worked correct again same problem @chqrlie – alizeyn Jan 21 '16 at 21:51
  • @AliZeynali: did you first remove the `save.dat` file? – chqrlie Jan 21 '16 at 23:01
  • I didn't remove but delete all data chqrlie – alizeyn Jan 21 '16 at 23:14
  • @AliZeynali: what do you mean by *delete all data*? did you delete the file with `del save.dat` or `rm save.dat` or `unlink("dave.dat");` or did you do something else? – chqrlie Jan 21 '16 at 23:22
  • I just opened file and delete every thing in file and save i didn't delete the file – alizeyn Jan 22 '16 at 03:41
  • Okay, if you do that, try running `hexdump save.dat` on the command line (assuming you're using a linux-style system). I reckon that the file won't actually be empty. You've somehow left some extra characters in there. Another way would be to look at the exact file size in bytes (it should be zero). Better to actually delete it before running your test. It may have got this way because you originally wrote data to it from an uninitialised array. Whatever editor you used to "delete" the contents might have left some unprintable characters in there. – paddy Jan 22 '16 at 04:09
  • THANKS CHQRLIE AND PADDY IT WORKED WHEN I DELETED WHOLE FILE(in last times i opened file and delete it's content but now i deleted file it self and let "ab" make its file and it worked :DDD i'm not on earth now:DDDDD – alizeyn Jan 22 '16 at 04:53