سؤال

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.

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

The notepad is obviously confusing the data you're writing with unicode byte order mark and gets into some funny state.

Consider how the data you're writing will look in binary and what it can possibly do to text editor.

when you open file you assign it to variable name plik

plik = fopen("E:\data.txt","r+b");

but you write to variable fl which is uninitialized.

fwrite((char*)d, sizeof(int), sizeof(int)*3,fl);

And the size for write should not multiply with sizeof(int).

fwrite((char*)d, sizeof(int), 3,fl);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top