C++ tellg() and tellp()

beginner
22 min

C++ tellg() and tellp()

Welcome to our deep dive into the fascinating world of C++! Today, we're going to explore the tellg() and tellp() functions, essential tools in managing files and streams in C++. Let's get started!

What are tellg() and tellp()? šŸŽÆ

In C++, tellg() and tellp() are stream manipulators that return the current position of a file or stream. They are incredibly useful when you need to keep track of your position while reading or writing to a file.

The tellg() Function šŸ“

tellg() is used with input streams, such as ifstream. It returns the current position indicator for the given input stream as a std::streamsize.

cpp
#include <iostream> #include <fstream> int main() { std::ifstream file("example.txt"); if (file.is_open()) { std::streamsize position = file.tellg(); std::cout << "Current position in the file: " << position << std::endl; file.close(); } return 0; }

In this example, we open a file named example.txt and get its current position using tellg().

The tellp() Function šŸ“

tellp() is used with output streams, such as ofstream. It returns the current position indicator for the given output stream as a std::streamsize.

cpp
#include <iostream> #include <fstream> int main() { std::ofstream file("example.txt"); if (file.is_open()) { file << "Hello, World!\n"; std::streamsize position = file.tellp(); std::cout << "Current position in the file: " << position << std::endl; file.close(); } return 0; }

In this example, we open a file named example.txt for writing, write "Hello, World!", get its current position using tellp(), and then close the file.

Using tellg() and tellp() together šŸ’”

You can use tellg() and tellp() together to perform some interesting operations, such as reading a specific amount of data from a file.

cpp
#include <iostream> #include <fstream> int main() { std::ifstream file("example.txt", std::ios::in | std::ios::out); std::streamsize fileSize = file.tellg(); std::streamsize bytesToRead = 5; if (file.is_open()) { char buffer[6]; file.seekg(bytesToRead); file.read(buffer, bytesToRead); buffer[bytesToRead] = '\0'; std::cout << "First 5 bytes: " << buffer << std::endl; // Move the position back to the beginning of the file file.seekg(0); // Write some new data to the file file << "New Data"; std::streamsize newFileSize = file.tellg(); std::cout << "New file size: " << newFileSize << std::endl; file.close(); } return 0; }

In this example, we open a file for both reading and writing, read the first 5 bytes, print them, move the position back to the beginning of the file, write some new data, and print the new file size.

Quiz šŸŽÆ

Quick Quiz
Question 1 of 1

What does the `tellg()` function return when used with an input stream?

That's all for today! We hope you found this lesson on tellg() and tellp() in C++ helpful. Stay tuned for more exciting lessons here at CodeYourCraft! šŸš€