我有一段代码,我在一些循环中执行,并希望得到具体的结果:
I have the block of code, which I execute in some cycle and expect to get concrete result:
代码: p>
The code:
fseek(file, start_seek_position, SEEK_SET); cout << "Cursor befor fgetc: " << ftell(file) << endl; fgetc(file); cout << "Cursor after fgetc: " << ftell(file) << endl << endl;期望:
Cursor befor fgetc: 76 Cursor after fgetc: 77 Cursor befor fgetc: 120 Cursor after fgetc: 121 Cursor befor fgetc: 170 Cursor after fgetc: 171strong>实际结果:
Real result:
Cursor befor fgetc: 76 Cursor after fgetc: 44 Cursor befor fgetc: 120 Cursor after fgetc: 94 Cursor befor fgetc: 170 Cursor after fgetc: 151为什么会发生这种情况?我认为 fgetc 应该将光标位置向前移动一个。
Why has this happened? I thought fgetc should move cursor position forward by one.
推荐答案该文件在文本模式而不是二进制模式。因此代替:
The issue could be that you opened the file in text mode instead of binary mode. So instead of this:
file = fopen(file_name, "r"); // open as text应该是这样:
#include <cstdio> file = fopen(file_name, "rb"); // open as binary stream, not textftell 和 fseek 在作为二进制流打开的文件上始终如一地工作(更符合要求 - 正常工作)。
Functions such as ftell and fseek work consistently (more to the point -- behave as expected) on files opened as a binary stream.
但是,当文件作为文本流打开时(只需指定r,而不是rb),将会出现行结束和文件结束字符翻译,因此总是会抛开 fseek 和 ftell 工作。
However, when a file is opened as a text stream (just specifying "r" instead of "rb"), there will be end-of-line and end-of-file character translations occurring, thus invariably throwing off the way that fseek and ftell work.
更多推荐
fgetc的奇怪行为
发布评论