File size c is different from the size data line size

I have a file that I write and then resize it to the size of the text written on it, for example:

FILE * file...

      

I am getting all data from a file and resizing the file to the size of the data, but it is different. The line size is smaller than the length of the file and shortens it and loses data. What could be the problem?

while(fgets(cLine, sizeof(cLine), file) )
    str.append((string)cLine);
fputs(str.c_str(),file);
_chsize( fileno(file), (int)str.size() );

      

When I checked it, there fileLength(fileno(file))

is always more than str.size()

!

+1


a source to share


3 answers


Perhaps it is CRLF? Beware:

fopen(filename, "r")

vs fopen(filename, "rb")

,

and

fopen(filename, "w")

vs fopen(filename, "wb")

.



The reason is that it will "r"

either "w"

translate CRLF and "rb"

or "wb"

will treat the data as binary. This is ignored on most platforms. For example, the fopen man page on OS X :

The mode string can also include the letter "b", either as the third character or as a character between characters in any of the two-character strings described above. This is strictly for compatibility with ISO / IEC 9899: 1990 ("ISO C90") and has no effect; "b" is ignored.

fopen page on MSDN says something different:

b

Open in binary (untranslated) mode; translations with translation and line feed characters are suppressed.

If t or b is not specified in mode, the default translation mode is defined by the global variable _ fmode . If t or b is prefixed to the argument, the function fails and returns NULL .

For more information on using text and binary modes in Unicode and multibyte stream I / O, see Text and Binary File I / O and Unicode I / O Stream in Text and Binary Mode .

+9


a source


Depending on what you are doing in your code for cr / lf and what OS you are running, there may be some translation running in the background while reading / writing the file if you open it in text mode.



+1


a source


Jonathan hit a nail on the head.

Make sure you are reading the file in binary format, or if you are sure that the file contains only text (which is all you need), then be prepared for the characters in the files to be in Unicode format or in another format.

You will also find that additional control characters are automatically added, not least to the EOF character.

My question is, though why are you reading data from a file, only to write it again?

+1


a source







All Articles