FILE *指针的末尾不等于写入数据的大小

时间:2020-03-06 14:50:15  来源:igfitidea点击:

简而言之,我有以下代码片段:

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.

这是为什么?为什么写入的字节数与文件指针不匹配?

解决方案

由于我们是在文本模式下打开文件的,因此它将行尾标记(例如LF)转换为CR / LF。

如果我们是在Windows上运行,则可能会出现这种情况(并且考虑到文件名以" c:"开头)。

如果我们以"" wb"`模式打开文件,我怀疑我们会发现数字是相同的:

FILE* test = fopen("C:\core.u", "wb");

C99标准在`7.19.5.3 fopen函数'中有这样的说法:

The argument mode points to a string. If the string is one of the following, the file is
  open in the indicated mode. Otherwise, the behaviour is undefined.
  
  r open text file for reading

  w truncate to zero length or create text file for writing

  a append; open or create text file for writing at end-of-file

  rb open binary file for reading

  wb truncate to zero length or create binary file for writing

  ab append; open or create binary file for writing at end-of-file

  r+ open text file for update (reading and writing)

  w+ truncate to zero length or create text file for update

  a+ append; open or create text file for update, writing at end-of-file

  r+b or rb+ open binary file for update (reading and writing)

  w+b or wb+ truncate to zero length or create binary file for update

  a+b or ab+ append; open or create binary file for update, writing at end-of-file

我们会看到它们区分" w"和" wb"。我不认为需要一种实现来区别对待两者,但是对二进制数据使用二进制模式通常更安全。

fwrite返回什么?通常,返回值应为写入的字节数。
另外,ftell()在fseek之前会回答什么?

了解什么操作系统,C编译器版本和C库可能会有所帮助。

文件指针是一个cookie。它没有价值。我们可以使用它的唯一目的是在文件中寻找相同的位置。我什至不确定ISO C是否保证ftell返回增加的值。如果我们不相信这一点,请查看不同的seek()模式。之所以存在它们,恰恰是因为该位置不是简单的字节偏移。

Windows实际上不会在没有刷新和可能没有fsync的情况下将所有数据写出到文件中。也许那就是为什么