C++ tellg和tellp函數用法詳解

2020-07-16 10:04:43
檔案流物件有兩個可用於隨機檔案存取的成員函數:tellptellg。它們的目的是將檔案讀寫位置的當前位元組編號作為一個 long 型別整數返回。

如果你了解 seekp 和 seekg 不難猜到,tellp 用於返回寫入位置,tellg 則用於返回讀取位置。假設 pos 是一個 long 型別的整數,那麼以下就是該函數的用法範例:

pos = outFile.tellp();
pos = inFile.tellg();

下面的程式演示了 tellg 函數的用法。它開啟了一個名為 letters.txt 檔案。檔案包含以下字元:

abcdefghijklmnopqrstuvwxyz

//This program demonstrates the tellg function.
#include <iostream>
#include <fstream>
#include <cctype> // For toupper
using namespace std;

int main()
{
    // Variables used to read the file
    long offset;
    char ch;
    char response; //User response
    // Create the file object and open the file
    fstream file("letters.txt", ios::in);
    if (!file)
    {
        cout << "Error opening file.";
        return 0;
    }
    // Work with the file
    do {
        // Where in the file am I?
        cout << "Currently at position " << file.tellg() << endl;
        // Get a file offset from the user.
        cout << "Enter an offset from the " << "beginning of the file: ";
        cin >> offset;
        // Read the character at the given offset
        file.seekg(offset, ios::beg);
        file.get(ch);
        cout << "Character read: " << ch << endl;
        cout << "Do it again? ";
        cin >> response;
    } while (toupper(response) == 'Y');
    file.close ();
    return 0;
}
程式輸出結果:

Currently at position 0
Enter an offset from the beginning of the file: 5
Character read: f
Do it again? y
Currently at position 6
Enter an offset from the beginning of the file: 0
Character read: a
Do it again? y
Currently at position 1
Enter an offset from the beginning of the file: 20
Character read: u
Do it again? n