C++ seekg() and seekp(): Navigating Files with Ease

beginner
8 min

C++ seekg() and seekp(): Navigating Files with Ease

Welcome to this comprehensive lesson on C++'s seekg() and seekp() functions! These powerful tools allow us to move around in files like a pro. Let's dive in, and by the end, you'll be navigating files with ease! šŸŽÆ

What are seekg() and seekp()?

seekg() and seekp() are part of the standard stream I/O library in C++. They are used to change the current position in a file stream, either for reading (seekg()) or writing (seekp()). Let's understand this with a simple example:

cpp
#include <iostream> #include <fstream> int main() { std::ofstream outFile("example.txt"); // Create a file outFile << "Hello, World!\n"; // Write to the file outFile.close(); // Close the file std::ifstream inFile("example.txt"); // Open the file inFile.seekg(std::ios::beg); // Move to the beginning of the file char c; while (inFile.get(c)) { // Read and display each character std::cout << c; inFile.seekg(1, std::ios::cur); // Move to the next position } inFile.close(); // Close the file return 0; }

In the above example, we create a file named example.txt, write a line, and then read it back. The seekg(1, std::ios::cur) function is used to move the file pointer to the next position after reading a character. šŸ’” Pro Tip: You can use std::ios::beg, std::ios::cur, and std::ios::end to specify the position in the file.

seekg() and seekp(): Real-World Application

Imagine building a text editor where you can move the cursor to a specific line and column. With seekg(), you can achieve this by changing the current position in the file. Similarly, in a log file reader, you can use seekg() to navigate to a specific log entry and read it.

Quiz Time!

Quick Quiz
Question 1 of 1

What does `std::ios::beg` represent in C++ stream I/O?

Practice Exercise

Create a simple program that reads a text file line by line and calculates the total number of words in it. Use seekg() to navigate to the next word each time.

Happy coding! If you have any questions or need help, feel free to ask. Keep learning, and let's build something amazing together! šŸ“