2

如果我运行:

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!

怎么会这样?

4

2 回答 2

8

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

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

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

于 2009-08-14T17:46:07.877 回答
1

It's a Windows thing. In text mode Windows expands '\n' to 'CR''LF' on writes, and compresses 'CR''LF' to '\n' on reads. Text mode is the default mode on windows. As Neil mentions, adding 'b' into the mode string of fopen() turns off newline translations. You won't have this translation on *nix systems.

于 2009-08-14T18:21:35.887 回答