我有一个正在写入的文件,然后将其大小更改为写入其中的文本大小,例如:
FILE * file...
我从文件中获取所有数据并将文件的大小更改为数据的大小,但它有所不同。字符串的大小小于文件长度,它会剪切它并丢失数据。 可能是什么问题?
while(fgets(cLine, sizeof(cLine), file) )
str.append((string)cLine);
fputs(str.c_str(),file);
_chsize( fileno(file), (int)str.size() );
当我检查它时,fileLength(fileno(file))
总是大于 str.size()
!
最佳答案
也许是 CRLF?注意:
fopen(filename, "r")
与 fopen(filename, "rb")
,
同样
fopen(filename, "w")
与 fopen(filename, "wb")
。
原因是因为"r"
或"w"
会翻译CRLF,而"rb"
或"wb"
会将数据视为二进制。在大多数平台上,这会被忽略。例如,fopen man page on OS X :
The mode string can also include the letter "b" either as a third character or as a character between the 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; the "b" is ignored.
fopen page on MSDN说点不一样的:
b
Open in binary (untranslated) mode; translations involving carriage-return and linefeed characters are suppressed.
If t or b is not given 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 about using text and binary modes in Unicode and multibyte stream-I/O, see Text and Binary Mode File I/O and Unicode Stream I/O in Text and Binary Modes.
关于c - 文件大小 c 不同于大小数据字符串的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/909043/