seekp/g and tellp/g does not work properly

这一生的挚爱 提交于 2019-12-11 07:47:01

问题


Whenever I try to use tellp/g and seekp/gfunctions on fstream object, and use the fstream::getline(cstr, bufsize) function, it just don't work properly and don't store anything in 'cstr' variable. and it does not report any problem which invalidate the stream like failbit or badbit

Sample code: what it does is read it line by line and on each read it jumps to the end of the file and print the next line's offset from the beginning of the file.

    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 after execution:

    abcd
    efg
    hi
    j
    5 6 7 8

But what was expected is:

    abcd
    efg
    hi
    j
    5 9 12 14

And the output from the shell is:

    abcd - 5
     - 6
     - 7
     - 8

Notice that there is nothing stored in the c variable

But what was expected from the shell is:

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

I want to point out that it's only the tellp/g() and seekp/g() functions that misses the fstream::getline() function. Using the following code:

    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;
    }

Notice: the tellp/g() and seekp/g() functions are stripped out

The shell outputs the following:

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

Can someone tell me why it behaves like this, And please I'm trying to understand this weird behavior I'm compiling with GCC-6.3.0-1 If there is any extra detail you want let me know

EDIT:

I've updated my compiler to GCC-8.2.0-3 and compiled normally and with -std=c++11/14/17 options but, still facing the same problem... Any suggestions will be super appreciated

来源:https://stackoverflow.com/questions/57537690/seekp-g-and-tellp-g-does-not-work-properly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!