HOW to get the current position within the file
时间: 2024-02-03 09:02:36 浏览: 37
To get the current position within a file in C++, you can use the tellg() function for input files and tellp() function for output files. These functions return the current position in the stream as a streampos object. Here's an example:
```
#include <fstream>
#include <iostream>
int main() {
std::ifstream input_file("example.txt");
if (!input_file.is_open()) {
std::cerr << "Failed to open file\n";
return 1;
}
// Get current position in file
std::streampos pos = input_file.tellg();
std::cout << "Current position: " << pos << '\n';
// Do some reading and move position
char c;
input_file >> c;
pos = input_file.tellg();
std::cout << "New position: " << pos << '\n';
input_file.close();
return 0;
}
```
This program opens a file "example.txt", gets the current position using tellg(), reads one character from the file, and gets the new position again. The output will show the two positions in the file.