fgetc的奇怪行为 [英] Strange behavior of fgetc

查看:156
本文介绍了fgetc的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段代码,我在一些循环中执行,并希望得到具体的结果:

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: 171

strong>实际结果:

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 text

ftell 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的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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