C++ tellg和tellp函数用法详解

文件流对象有两个可用于随机文件访问的成员函数: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