为什么 fwrite 写的比我告诉它的多?
FILE *out=fopen64("text.txt","w+");
unsigned int write;
char *outbuf=new char[write];
//fill outbuf
printf("%i\n",ftello64(out));
fwrite(outbuf,sizeof(char),write,out);
printf("%i\n",write);
printf("%i\n",ftello64(out));
输出:
0
25755
25868
发生了什么事? write 设置为 25755,我告诉 fwrite 将那么多字节写入文件,该文件位于开头,然后我位于 25755 之外的位置?
FILE *out=fopen64("text.txt","w+");
unsigned int write;
char *outbuf=new char[write];
//fill outbuf
printf("%i\n",ftello64(out));
fwrite(outbuf,sizeof(char),write,out);
printf("%i\n",write);
printf("%i\n",ftello64(out));
output:
0
25755
25868
what is going on?
write is set to 25755, and I tell fwrite to write that many bytes to a file, which is at the beginning, and then im at a position besides 25755?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您使用的是 DOSish 系统(例如 Windows)并且文件不是以二进制模式打开的,则行结束符将自动转换,并且每个“行”将添加一个字节。
因此,指定
"wb"
作为模式,而不仅仅是 @caf 指出的"w"
。它不会对类 Unix 平台产生任何影响,并且会在其他平台上做正确的事情。例如:
使用 VC++:
使用 Cygwin gcc:
If you are on a DOSish system (say, Windows) and the file is not opened in binary mode, line-endings will be converted automatically and each "line" will add one byte.
So, specify
"wb"
as the mode rather than just"w"
as @caf points out. It will have no effect on Unix like platforms and will do the right thing on others.For example:
With VC++:
With Cygwin gcc:
这可能取决于您打开文件的模式。如果以文本文件方式打开,那么在DOS/Windows系统中
\n
可能会写成\r\n
。但是,ftello64() 可能只给出二进制文件指针,该指针将计入写入的额外\r
字符中。尝试清除outbuf[]
中的任何\n
数据,或尝试以二进制方式打开 out 文件("wb"
而不是" w"
)。It may depend on the mode in which you opened the file. If you open it as a text file, then
\n
may be written as\r\n
in DOS/Windows systems. However,ftello64()
probably only gives the binary file pointer, which would count in the extra\r
characters written. Try clearing theoutbuf[]
of any\n
data or try opening the out file as binary ("wb"
instead of"w"
).变量 write 未初始化,因此数组的大小和写入的数量本质上是随机的。
The variable
write
is uninitialized and so the size of the array and the amount written will be essentially random.有趣的。在 Windows VC++ 上运行良好,尽管
ftello64
替换为ftell
。Interesting. Works fine on Windows VC++, albeit
ftello64
replaced withftell
.