fgetc的奇怪行为

编程入门 行业动态 更新时间:2024-10-08 20:39:54
本文介绍了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的奇怪行为

本文发布于:2023-11-27 09:53:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1637585.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:奇怪   fgetc

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!