c - 文件大小 c 不同于大小数据字符串的大小

标签 c windows file

我有一个正在写入的文件,然后将其大小更改为写入其中的文本大小,例如:

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/

相关文章:

java - Java中不循环地迭代某个目录中的文件

c - 读取值并将其存储在主变量中时出现问题吗?

cs50 pset5 为什么我的图像恢复程序只能恢复 50 个图像中的 49 个?

windows - Bamboo远程构建代理安装nodejs后找不到powershell.exe

windows - 错误 403 Wamp phpmyadmin

Windows 下的 Phpize

java - Eclipse 项目无法使用相对路径引用文件

file - 在 gnuplot 中读取外部数据文件

c - 如何在 C 中将 .o 文件转换回 .c 文件?

c - 如何使用共享内存传输FILE结构(POSIX SKIN)