Print from center of file
Write a program that opens a file named example.txt, moves the file position marker to the middle of the file using the seekg() function, and reads and prints the remaining content of the file from that point onward.
Hint
- You can get the size of the file by moving the position marker to the end (
seekg(0, std::ios::end)) and getting the position (tellg()). - You can store position markers in
std::streampos.
Answer
#include <iostream>
#include <fstream>
int main() {
std::ifstream inFile("example.txt", std::ios::in | std::ios::binary);
if (!inFile) {
std::cerr << "Error: Could not open the file example.txt." << std::endl;
return 1;
}
// Calculate the file size
inFile.seekg(0, std::ios::end);
std::streampos fileSize = inFile.tellg();
// Calculate the middle position
std::streampos middlePos = fileSize / 2;
// Move the file position marker to the middle
inFile.seekg(middlePos, std::ios::beg);
// Read and print the rest of the file
std::string line;
std::cout << "Reading from the middle of the file:" << std::endl;
while (std::getline(inFile, line)) {
std::cout << line << std::endl;
}
inFile.close();
return 0;
}