Search code examples
cfilefopenfwrite

C fwrite and file size


I'm confused of a strange problem. When I make something like below:

FILE* fl;
int* d = new int[3];
d[0] = -3;
d[1] = -3;
d[2] = -3;

plik = fopen("E:\data.txt","r+b");
fwrite((char*)d, sizeof(int), sizeof(int)*3, fl);
fclose(fl);
system("pause");

It writes correctly some data to the file, witch I can clean in notepad and get 0B file size. But if I change -3 to -2:

FILE* fl;
int* d = new int[3];
d[0] = -2;
d[1] = -2;
d[2] = -2;

plik = fopen("E:\data.txt","r+b");
fwrite((char*)d, sizeof(int), sizeof(int)*3,fl);
fclose(fl);
system("pause");

the result is that, when I clean the data in Notepad and save file, it have always 2B, and can't be cleaned to the end. What is the problem?. Thanks in advance.


Solution

  • You are writing binary data to a file and then opening it with a text editor. The result is UNDEFINED. When you see that word "UNDEFINED" in documentation, pay attention. It is your responsibility to not do things like that. A text editor is for opening text files, which means strings. The way to write an int into a text file is to do something like:

    char str[BIGNUMBER];
    sprintf(str, "%d", d[0]);
    fwrite...
    

    That is probably not what you wanted but it is the only way to get a Notepad compatible text file. What you probably want to do is to find a binary file editor that can open, display and edit binary files. Personally I just use vim with the -b option, even on Windows.