C++ tellg和tellp函数用法详解
发布时间:2020-12-16 07:37:34 所属栏目:百科 来源:网络整理
导读:文件流对象有两个可用于随机文件访问的成员函数: tellp 和 tellg 。它们的目的是将文件读写位置的当前字节编号作为一个 long 类型整数返回。 如果你了解 seekp 和 seekg 不难猜到,tellp 用于返回写入位置,tellg 则用于返回读取位置。假设 pos 是一个 long
文件流对象有两个可用于随机文件访问的成员函数:tellp 和 tellg。它们的目的是将文件读写位置的当前字节编号作为一个 long 类型整数返回。 如果你了解 seekp 和 seekg 不难猜到,tellp 用于返回写入位置,tellg 则用于返回读取位置。假设 pos 是一个 long 类型的整数,那么以下就是该函数的用法示例:
pos = outFile.tellp(); 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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |