seekp / g和tellp / g无法正常工作

时间:2019-08-17 15:39:11

标签: c++ io fstream iostream getline

每当我尝试在tellp/g对象上使用seekp/gfstream函数并使用fstream::getline(cstr, bufsize)函数时,它只是无法正常工作并且不存储'cstr'变量中的任何内容。并且不会报告任何使流无效的问题,例如failbitbadbit

示例代码:它所做的是一行一行地读取它,并且每次读取时,它会跳到文件的末尾并打印与文件开头的下一行的偏移量。

    int main()
    {

      // Prepare file
      fstream f("test.txt", fstream::ate | fstream::in | fstream::out);

      // Prepare needed data for production
      auto end_mark = f.tellg();
      size_t count{0};
      char c[64];

      // Go back to the beginning 
      f.seekg(0, fstream::beg);

      while(f && f.tellg() != end_mark && f.getline(c, 64))
        {
          count += f.gcount();

          auto mark = f.tellg();
          // Go to the end
          f.seekp(0, fstream::end);

          f << count; // print the next line's offset
          if(mark != end_mark) f << " ";

          // print results on shell ..For debug purposes
          cout << c << " - " << count << endl;

          // Go back to the last read point
          f.seekp(mark);
        }
      return 1;
    }

test.txt:

    abcd
    efg
    hi
    j

test.txt执行后:

    abcd
    efg
    hi
    j
    5 6 7 8

但是期望的是:

    abcd
    efg
    hi
    j
    5 9 12 14

shell的输出是:

    abcd - 5
     - 6
     - 7
     - 8

请注意,c变量中没有存储任何内容

但是从shell期望的是:

    abcd - 5
    efg - 9
    hi - 12
    j - 14

我要指出,只有tellp/g()seekp/g()函数遗漏了fstream::getline()函数。使用以下代码:

    int main()
    {
      // Prepare file
      fstream f("test.txt", fstream::in | fstream::out);

      size_t count{0};
      char c[64];

      while(f && f.getline(c, 64))
        {
          count += f.gcount();

          // print results on shell ..For debug purposes
          cout << c << " - " << count << endl;
        }
      return 1;
    }

注意:tellp/g()seekp/g()函数被剥离

shell输出以下内容:

    abcd - 5
    efj - 9
    hi - 12
    j - 14

有人可以告诉我为什么会这样吗,请尝试理解这种奇怪的行为 我正在使用GCC-6.3.0-1进行编译 如果您需要其他任何详细信息,请告诉我

编辑:

我已经将编译器更新为GCC-8.2.0-3并可以正常编译并使用-std = c ++ 11/14/17选项,但是仍然面临相同的问题... 任何建议将不胜感激

0 个答案:

没有答案