Syntax and Parameters of the Seekg() Function in C++
Seekg() can be implemented with two syntaxes:
1. Streampos Syntax
This syntax takes only one parameter, position, which represents the position of the cursor in the stream buffer. It represents an “int” value and of type streampos.
2. Offset and Direction Syntax
This syntax takes two parameters as input: offset and direction. The “ofst” parameter is an integer of type streamoff that indicates the offset in the stream’s buffer. The “dirt” parameter seeks direction.
- ios_base::beg: Offset from the very start of the stream’s buffer.
- ios_base::cur: Offset from the current position in the stream’s buffer.
- ios_base::end: Offset from the last of the stream’s buffer.
The seekg() function in C++ manipulates the file pointer, enabling the programmer to position it at a specific location within the file. It returns the modification of the “istream” object (*this) and adjusts the file pointer accordingly.
Error and Exception Handling in C++ Seekg() Function
The seekg() function in C++ ensures the basic guarantee for exception handling, maintaining the object validity if an exception occurs. It may throw the “failure” exceptions when the error state flag lacks information, and the function responsibly catches and manages these exceptions, rethrowing them if a bad bit was set in the last call.
Moreover, a common issue with seekg() occurs when it reaches the end-of-file (EOF), causing the pointer to remain unset and triggering an error. The clear() method is utilized to reset the pointer and resolve the EOF-related errors to address this. Additionally, seekg() may risk altering a stream object in a multithreaded environment, necessitating caution and the implementation of synchronization mechanisms to mitigate the potential “ofstream” object alterations.
Example 1: Basics of Seekg()
In the first example, we will explain the basics of the seekg() function in C++. The code of a C++ program is given in the following. Have a look at it first and then we will move on to the explanation of each section of the code.
#include <iostream>
using namespace std;
int main(int argc, char** argv){
fstream sgFile("seekgFile.txt",ios::in | ios::out | ios::trunc);
sgFile << "seekg() function";
sgFile.seekg(8, ios::beg);
char sgArray[8];
sgFile.read(sgArray, 8);
sgArray[8] = 0;
cout << sgArray << endl;
sgFile.close();
}
The program includes two necessary header files – <fstream> and <iostream> – for file handling and input/output operations, respectively. Afterwards, the “using namespace std;” statement is included, allowing the standard C++ identifiers without specifying the namespace explicitly. Finally, the main function begins, which is the program’s entry point, taking the command-line arguments (argc and argv).
fstream sgFile(“seekgFile.txt”, ios::in | ios::out | ios::trunc); – Here, the “sgFile”, an object of the “fstream” class, is created, representing a file stream. The file named “seekgFile.txt” is associated with the file stream. The file stream is opened for input (ios::in) output (ios::out). If the file exists, its contents are truncated (ios::trunc).
sgFile << “seekg() function”; – The “seekg() function” string is written to the file using the “<<” operator.
sgFile.seekg(8, ios::beg); – The seekg() function is used to set the get pointer at the 8th position from the beginning (ios::beg) of the file.
sgFile.read(sgArray, 8); – The “read” function is employed to read eight characters from the current position of the get pointer into the “sgArray”.
sgArray[8] = 0; – Null terminates the character array to ensure a proper string handling.
cout << sgArray << endl; – The content of “sgArray” (the 8 characters read from the file) is displayed on the console using cout.
sgFile.close(); – The close() function is used to close the file stream.
The output is of this program is expected to be “function”. Let us check it in the following output snippet:
The code creates a file stream that is associated with the “seekgFile.txt” file writes a string to the file, seeks the 8th position from the beginning, reads eight characters, and outputs the read content. Finally, the file stream is closed.
Example 2: Dynamic Navigation
Consider a scenario where you must dynamically calculate the seekg() offset. Let us understand how to dynamically calculate the offset with the help of a code example.
#include <fstream>
using namespace std;
int main() {
ifstream sgFile("seekgFile.txt");
int offset = 8;
sgFile.seekg(offset, ios::cur);
char buffer[8];
sgFile.read(buffer, 8);
cout << "Content: " << buffer << endl;
sgFile.close();
return 0;
}
As you can see, we are reading the content from the same file which we created in the previous example, “seekgFile.txt”. The seekg() function sets the get pointer at the current position (ios::cur) in the file, and it is moved by the calculated offset (8 characters). The read() function reads eight characters from the current position of the get pointer into the buffer.
Given the content of the “seekg() function” file and the offset of eight characters, the program will output the substring that starts from the 9th character of the file. Therefore, the expected result of the program is “function”. Let us confirm it in the following given output:
This example demonstrates the flexibility of seekg() by dynamically calculating the offset.
Example 3: Navigating from the End
In this example, we will demonstrate how to read the data in a file from the end of the file. Here, seekg() is used to navigate from the end of the file. The negative offset indicates a position that is relative to the end. See the following given code:
#include <fstream>
using namespace std;
int main() {
ifstream sgFile("seekgFile.txt");
sgFile.seekg(-4, ios::end);
char buffer[8];
sgFile.read(buffer, 8);
cout << "Content: " << buffer << endl;
sgFile.close();
return 0;
}
This C++ program opens a file named “seekgFile.txt” which moves the get pointer of four characters backward from the end of the file using sgFile.seekg(-4, ios::end), reads the next eight characters from that position into a buffer, and then prints the content of the buffer to the console. Given the content of the file as “seekg() function”, the expected output is “ction”. Let us match the output in the screenshot of the following output:
Conclusion
In summary, seekg() emerges as a valuable asset for navigating the file streams with precision. Through its ability to seek arbitrary positions, dynamically calculate the offsets, and navigate from different points within a file, seekg() empowers the developers to handle the file operations efficiently. As we’ve seen in the examples, mastering seekg() enhances your control and flexibility when working with file streams in C++. However, it demands a careful consideration of exception handling and potential data race scenarios to ensure the robust and error-free file operations in C++.