簡體   English   中英

C ++文件處理中的tellg()是什么?它如何工作?

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

我嘗試使用tellg()訪問要從文件讀取的下一個字符,如果文件有一行文本,則正確返回位置。但是,如果文件多於一行,則會給我一些異常值。正在附加我的代碼和我在下面的輸出。

   #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行從2 ..開始打印時,有人可以向我解釋..嗎?

實際上,tellg()不是返回流中字節的偏移量,而是返回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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM