【问题标题】:Why seekg function doesn't work?为什么 seekg 功能不起作用?
【发布时间】:2013-02-07 13:53:23
【问题描述】:

代码如下:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main(int argc, char *argv[])
{
  string infile(argv[1]);
  ifstream fin(infile.data());

  string var_name;
  char ch = fin.get();
  cout << ch << endl;

  ch = fin.get();
  cout << ch << endl;

  ch = fin.get();
  cout << ch << endl;

  cout << "pos: " << fin.tellg() << endl;
  fin.seekg(-sizeof(char),ios::cur);
  cout << "pos: " << fin.tellg() << endl;

  ch = fin.get();
  cout << ch << endl;

  return 0;
}

文件内容只是一个字符串:

<
?
x
m

输出是:

<\n
?\n
x\n
pos: 3\n
pos: 2
x

为什么最后打印的字符还是'x'??为什么 seekg 函数不将文件指针向后移动一个字节?

【问题讨论】:

    标签: c++ file get seekg


    【解决方案1】:

    在读取 x 之后文件指针的位置是 3,但 x 本身位于位置 2(因为第一个字符位于位置 0)。向后移动 1 个字符会将文件指针放在它最近读取的字符处,这正是这里发生的情况。

    如果你想移动到读取最后一个字符之前的那个字符,你需要按-2而不是-1来寻找。

    【讨论】:

      【解决方案2】:

      如果您这样做,它将起作用:fin.seekg(-sizeof(char)-1,ios::cur);

      注意:寻找文本文件中的任意位置是未定义行为。见这里:How to read the 6th character from the end of the file - ifstream?

      【讨论】:

      • sizeof(char) 始终为 1。你不妨写成 -2。
      • 这是为了完整性:-P @Alex。如果我这样写,OP 会理解,因为他曾尝试像 -sizeof(char) 这样写。
      • 那么应该是-sizeof(char)*2 :)
      猜你喜欢
      • 2015-10-09
      • 2015-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多