C++ tellg和tellp函数用法详解
文件流对象有两个可用于随机文件访问的成员函数:tellp 和 tellg。它们的目的是将文件读写位置的当前字节编号作为一个 long 类型整数返回。
如果你了解 seekp 和 seekg 不难猜到,tellp 用于返回写入位置,tellg 则用于返回读取位置。假设 pos 是一个 long 类型的整数,那么以下就是该函数的用法示例:
如果你了解 seekp 和 seekg 不难猜到,tellp 用于返回写入位置,tellg 则用于返回读取位置。假设 pos 是一个 long 类型的整数,那么以下就是该函数的用法示例:
pos = outFile.tellp();
pos = inFile.tellg();
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
所有教程
- socket
- Python基础教程
- C#教程
- MySQL函数
- MySQL
- C语言入门
- C语言专题
- C语言编译器
- C语言编程实例
- GCC编译器
- 数据结构
- C语言项目案例
- C++教程
- OpenCV
- Qt教程
- Unity 3D教程
- UE4
- STL
- Redis
- Android教程
- JavaScript
- PHP
- Mybatis
- Spring Cloud
- Maven
- vi命令
- Spring Boot
- Spring MVC
- Hibernate
- Linux
- Linux命令
- Shell脚本
- Java教程
- 设计模式
- Spring
- Servlet
- Struts2
- Java Swing
- JSP教程
- CSS教程
- TensorFlow
- 区块链
- Go语言教程
- Docker
- 编程笔记
- 资源下载
- 关于我们
- 汇编语言
- 大数据
- 云计算
- VIP视频