FILE *指针的端部不等于写入的数据的大小 [英] End of FILE* pointer is not equal to size of written data

查看:204
本文介绍了FILE *指针的端部不等于写入的数据的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很简单地说,我有以下的code片断:

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);

和它输出:

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?

推荐答案

既然你打开在文本模式下的文件,它会转换尾行标记,如LF,到CR / LF

Since you're opening the file in text mode, it will convert end-of-line markers, such as LF, into CR/LF.

此,如果你在Windows上运行的可能是(你也许是,因为你的文件名以启动C:\\)。

This is likely if you're running on Windows (and you probably are, given that your file name starts with "c:\").

如果你打开​​文件WB模式下,我怀疑你会发现这些数字是相同的:

If you open the file in "wb" mode, I suspect you'll find the numbers are identical:

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

C99标准有这样的说7.19.5.3函数fopen

的参数mode指向一个字符串。如果字符串是以下情况之一,该文件是
  在显示模式下打开。否则,行为是不确定的。

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.

研究读取结果打开文本文件
  是W 截断至零长度或编写结果创建文本文件
   A 追加;打开或在档案结尾结果写入创建文本文件
   RB 打开二进制文件进行读取结果
   WB 截为零或建立文字搜索二进制文件
   AB 追加;打开或在档案结尾结果写入创建的二进制文件
   R + 更新的模式(读,写)打开文本文件结果
   W + 截为零或创建更新结果的文本文件
   A + 追加;打开或创建更新的文本文件,在档案结尾结果写
   R + B RB + 进行更新开放二进制文件(阅读和写作)结果
  W¯¯+ B WB + 截为零或创建更新的结果二进制文件
   A + B AB + 追加;打开或创建更新二进制文件,在结束文件写入

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 。我不相信一个实现的需要的对待这两个不同,但它通常使用更安全二进制模式二进制数据。

You can see they distinguish between w and wb. 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.

这篇关于FILE *指针的端部不等于写入的数据的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆