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
所有教程
- C语言入门
- C语言编译器
- C语言项目案例
- 数据结构
- C++
- STL
- C++11
- socket
- GCC
- GDB
- Makefile
- OpenCV
- Qt教程
- Unity 3D
- UE4
- 游戏引擎
- Python
- Python并发编程
- TensorFlow
- Django
- NumPy
- Linux
- Shell
- Java教程
- 设计模式
- Java Swing
- Servlet
- JSP教程
- Struts2
- Maven
- Spring
- Spring MVC
- Spring Boot
- Spring Cloud
- Hibernate
- Mybatis
- MySQL教程
- MySQL函数
- NoSQL
- Redis
- MongoDB
- HBase
- Go语言
- C#
- MATLAB
- JavaScript
- Bootstrap
- HTML
- CSS教程
- PHP
- 汇编语言
- TCP/IP
- vi命令
- Android教程
- 区块链
- Docker
- 大数据
- 云计算