Seekg Function In C++ - C++ Programming Tutorial
C++ Course / Functions / Seekg Function In C++

Seekg Function In C++

BLUF: Mastering Seekg Function In C++ is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Seekg Function In C++

C++ is renowned for its efficiency. Learn how Seekg Function In C++ enables low-level control and high-performance computing in the tutorial below.

Introduction:

In this guide, we will explore the seekg method in C++. The seekg operation allows for navigating to any specific file location within the iostream library. This function is an integral part of file manipulation and is located within the fstream header file. Its primary purpose is to read from the input stream by moving the pointer to the next desired character's position.

Syntax of seekg function:

The seekg function offers two different syntax options that can be utilized:

1 st syntax:

Example

istream&seekg(streampos position);

2 nd syntax:

Example

istream&seekg(streamoff offset, ios_base::seekdirdir);

Seekg's parameters in C++:

There are different arguments for the seekg method in C++. These arguments include:

Position

The streampos data type is employed for positioning the pointer at a particular location within the stream buffer through the use of an integer value. In narrow-oriented streams, positions are denoted by a streampos instance belonging to the fpos class. Instances of this class facilitate uniform conversions to and from streamoff values, along with the creation and conversion from integers.

It refers to the positions specified by the variables iosbase::beg, iosbase::cur, and ios_base::end, which indicate the start, current position, and conclusion of the file.

offset

It is employed to navigate directories and belongs to the streamoff data type. The pointer moves to the directory specified by the offset value.

Return Value of the seekg function

In C++, the seekg method positions the file pointer to the specified location within the file. This action adjusts the file pointer and then provides the istream object (*this) as output.

Seekg exceptions in C++

In fundamental guarantee, the object remains valid even when an exception is triggered. A failure exception of member type will be raised if the error state flag fails to adequately indicate the result and member exceptions were configured for that particular state.

The function captures and manages any exception thrown, while also handling any errors generated by internal processes. In case a previous call to exceptions resulted in an error, the function will throw the same exception that was caught.

Problems Found:

Utilize the clear function to reset the pointer if it reaches the end of the file to prevent a failure of the seekg function and ensure the pointer is properly reset.

Races in Data:

The stream object is modified, which can lead to potential data races when the same stream object is concurrently accessed. Data races occur when multiple locations access the stream object simultaneously.

How does the seekg function operate in C++?

There are two approaches for using the seekg function. These techniques are outlined below:

  1. Istream &Seekg (streampos position):

The position is the parameter that dictates the change in pointer location.

Algorithm:

Firstly, create a fresh document for input/output tasks. For example, name the file as "jtp.txt". Set the file's current position to 2. Insert some text into the file, like "welcome to JTP". Move the pointer from its current position to skip 3 characters or advance to 5.

Write the content of the file to the buffer before closing the buffer.

Use the function

  1. to set the position within the input stream.

A pointer's offset refers to the value it skips over and progresses to. The initial direction of the pointer is denoted by the letter dir.

Algorithm:

First, create a fresh file for Input/Output tasks. As an example, designate the file name as "jtp2.txt". Append additional characters to the file once again. For instance, have it display "greetings from jtp" this time. Locate and retrieve the initial 3 characters, which is now "gre".

Based on the preceding two techniques, the code will appear as shown below:

jtp.seekg(3) ;

jtp2.seekg(3, ios::beg) ;

Examples of Seekg functions in C++

Let's take an example of the seekg function with offset in the code that follows:

  • Check out a file from the filesystem.
  • Include some text there.
  • Find the file's first 4 characters.
  • The contents of the file's following five characters are copied into a buffer.
  • Print the data in the buffer.

Code:

Example

#include <iostream>
#include <fstream>
#include <string>

int main() {
std::ifstreaminFile("data.txt"); // Open the file in read mode
    if (!inFile.is_open()) {
std::cout<< "Error opening the file.\n";
        return 1;
    }

std::string fileContent;
std::getline(inFile, fileContent);

    // Add some text to the file's contents
fileContent += " Welcome to the file!";

    // Close and re-open the file in write mode to clear its contents
inFile.close();
std::ofstreamoutFile("data.txt", std::ios::trunc);
    if (!outFile.is_open()) {
std::cout<< "Error opening the file for writing.\n";
        return 1;
    }

    // Write the modified content back to the file
outFile<<fileContent;
outFile.close();

    // Re-open the file in read mode to perform the seek operation
std::ifstreamseekFile("data.txt");
    if (!seekFile.is_open()) {
std::cout<< "Error opening the file for reading.\n";
        return 1;
    }

    // Seek the first 4 characters from the file
seekFile.seekg(4);

    // Copy the next 5 characters from the file's contents into a buffer
const int bufferSize = 5;
    char buffer[bufferSize + 1]; // +1 for null-terminator
seekFile.read(buffer, bufferSize);
    buffer[bufferSize] = '\0'; // Null-terminate the buffer

    // Print the buffer data
std::cout<< "Copied data from the file: " << buffer << std::endl;

    // Close the file
seekFile.close();

    return 0;
}

Output:

Output

Copied data from the file: o, th

Conclusion:

The seekg method is utilized in C++ programming to assist in retrieving a specific file position within the iostream library. This function can be used in two ways: istream&seekg(streampos position) and istream&seekg(streamoff offset, ios_base::seekdirdir).

The integer value is employed to assign the pointer to a particular position within the stream buffer indicated by the parameter position of type streampos, a concept commonly used in coding.

The orientation is determined by the iosbase::beg, iosbase::cur, and ios_base::end values within the argument. The dir represents the orientation towards the start of the file, the present position, and the conclusion.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience