FILE* 指针结尾不等于写入数据的大小
非常简单地说,我有以下代码片段:
FILE* test = fopen("C:\\core.u", "w");
printf("Filepointer at: %d\n", ftell(test));
fwrite(data, size, 1, test);
printf("Written: %d bytes.\n", size);
fseek(test, 0, SEEK_END);
printf("Filepointer is now at %d.\n", ftell(test));
fclose(test);
它输出:
Filepointer at: 0
Written: 73105 bytes.
Filepointer is now at 74160.
这是为什么? 为什么写入的字节数与文件指针不匹配?
Very simply put, I have the following code snippet:
FILE* test = fopen("C:\\core.u", "w");
printf("Filepointer at: %d\n", ftell(test));
fwrite(data, size, 1, test);
printf("Written: %d bytes.\n", size);
fseek(test, 0, SEEK_END);
printf("Filepointer is now at %d.\n", ftell(test));
fclose(test);
and it outputs:
Filepointer at: 0
Written: 73105 bytes.
Filepointer is now at 74160.
Why is that? Why does the number of bytes written not match the file pointer?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
由于您以文本模式打开文件,因此它会将行尾标记(例如 LF)转换为 CR/LF。
如果您在 Windows 上运行,则很可能会出现这种情况(考虑到您的文件名以
"c:\"
开头)。如果您以“wb”模式打开文件,我怀疑您会发现数字是相同的:
C99 标准在
7.19.5.3 The fopen function
中有这样的说法:您可以看到它们区分
w
和wb
。 我不认为需要实现来区别对待这两者,但对二进制数据使用二进制模式通常更安全。Since you're opening the file in text mode, it will convert end-of-line markers, such as LF, into CR/LF.
This is likely if you're running on Windows (and you probably are, given that your file name starts with
"c:\"
).If you open the file in
"wb"
mode, I suspect you'll find the numbers are identical:The C99 standard has this to say in
7.19.5.3 The fopen function
:You can see they distinguish between
w
andwb
. I don't believe an implementation is required to treat the two differently but it's usually safer to use binary mode for binary data.fwrite 返回什么? 通常返回值应该是写入的字节数。
另外,ftell() 在 fseek 之前回答什么?
了解操作系统、C 编译器版本和 C 库可能会有所帮助。
what does fwrite return? normally the return value should be the number of bytes written.
Also, what does the ftell() answer with right before the fseek?
It might help to know what operating system, C compiler version and C library.
文件指针是一个 cookie。 它没有任何价值。 您可以使用它的唯一用途是查找文件中的同一位置。 我什至不确定 ISO C 是否保证 ftell 返回递增的值。 如果你不相信这一点,请看看不同的seek()模式。 它们的存在正是因为位置不是简单的字节偏移。
A filepointer is a cookie. It has no value. The only thing you can use it for is to seek to the same place in a file. I'm not even sure if ISO C guarantees that ftell returns increasing values. If you don't believe this, please look at the different seek() modes. They exist precisely because the position is not a simple byte offset.
Windows 实际上不会在没有刷新和可能的 fsync 的情况下将所有数据写入文件。 也许这就是原因
windows doesn't actually write all data out to the file without a flush and possibly an fsync. Maybe that's why