c++ 文件处理中的 tellg() 是什么,它是如何工作的?

What is tellg() in file handling in c++ and how does it work?

如果文件只有一行文本,我尝试使用 tellg() 和 returns 正确位置访问要从文件中读取的下一个字符。但是当文件超过一行给了我一些异常值..我附上了我的代码和下面的输出..

   #include <iostream>
   #include <fstream>

   using namespace std;

   int main()
   {
       char temp;
       ifstream ifile("C:\Users\admin\Desktop\hello.txt");
       ifile>>noskipws;
       while(ifile>>temp)
       {
           cout<<temp<<" "<<ifile.tellg()<<endl;
       }
   }

   output:
      H 3
      e 4
      l 5
      l 6
      o 7

        8
      W 9
      o 10
      r 11
      l 12
      d 13
      . 14
      . 15

        16
      ! 17
      ! 18
      ! 19

    File : Hello.txt contains 3 lines as given below..

           Hello
           World
           !!!

不明白为什么它在打印语句中以 3 开头,而应该从 1 开始。当有 2 行时,它从 [=14] 开始打印=].. 谁能给我解释一下..?

事实上,tellg() 不是 return 流中字节的偏移量,而是 pos_type 可由 seekg() 重用的描述符。如果文件是二进制文件,它将匹配字节偏移量,但在文本流中不能保证。 (在 *ix 中它也会匹配,但在 Windows 中没有直接赋值。)

以二进制方式打开文件,因为seekg()是带偏移量使用的。如果文件的修改发生在程序的两次运行之间,则需要将 positionEof 存储在文件中。

注意:在二进制模式下,您实际上可以将 positionEof 存储为整数,但我更喜欢尽可能使用显式类型。

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    streampos positionEof;

    // Record original eof position.
    ifstream instream("C:\Users\istvan\Desktop\hello.txt", ios::in | ios::binary);
    if (instream.is_open()) {
        instream.seekg(0, ios::end);
        positionEof = instream.tellg();     // store the end-of-file position
        instream.close();
    }
    else
        cout << "Record eof position: file open error" << endl;

    // Append something to the file to simulate the modification.
    ofstream outstream("C:\Users\istvan\Desktop\hello.txt", ios::app);
    if (outstream.is_open()) {
        cout << "write" << endl;
        outstream << "appended text";
        outstream.close();
    }

    // Check what was appended.
    instream.open("C:\Users\istvan\Desktop\hello.txt", ios::in | ios::binary);
    if (instream.is_open()) {
        instream.seekg(positionEof);    // Set the read position to the previous eof
        char c;
        while ( instream.get(c))
            cout << c;

        instream.close();
    }
    else
        cout << "Check modification: file open error!" << endl;

    return 0;
}