【问题标题】:c++ fread changing fgetpos strangelyc ++ fread奇怪地改变了fgetpos
【发布时间】:2010-11-19 17:36:51
【问题描述】:

如果我跑:

FILE* pFile = fopen("c:\\08.bin", "r");
fpos_t pos;
char buf[5000];

int ret = fread(&buf, 1, 9, pFile);
fgetpos(pFile, &pos);

我得到 ret = 9 和 pos = 9。

但是如果我运行

FILE* pFile = fopen("c:\\08.bin", "r");
fpos_t pos;
char buf[5000];

int ret = fread(&buf, 1, 10, pFile);
fgetpos(pFile, &pos);

ret = 10 符合预期,但 pos = 11!

这怎么可能?

【问题讨论】:

    标签: c++ fread fgetpos


    【解决方案1】:

    这是 Windows 的事情。在文本模式下,Windows 在写入时将 '\n' 扩展为 'CR''LF',在读取时将 'CR''LF' 压缩为 '\n'。文本模式是 Windows 上的默认模式。正如 Neil 提到的,在 fopen() 的模式字符串中添加 'b' 会关闭换行符翻译。您不会在 *nix 系统上进行此翻译。

    【讨论】:

      【解决方案2】:

      需要以二进制方式打开文件:

      FILE * pFile = fopen("c:\\08.bin", "rb"); 
      

      不同之处在于读取库认为是换行符的字符并将其扩展 - 二进制模式阻止扩展。

      【讨论】:

      • 如 C 标准中所述:“[由 fgetpos()] 存储的值包含 fsetpos 函数可用于在调用 fgetpos 函数时将流重新定位到其位置的未指定信息。”
      猜你喜欢
      • 2014-07-03
      • 2019-08-10
      • 2018-11-28
      • 2019-05-17
      • 1970-01-01
      • 2011-09-22
      • 2011-03-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多