This blog is about providing theory as well as simple executable codes of different programming languages such as java, C, C++, and web programming, etc. This blog will be helpful to the IT students to learn about programming.

Tuesday, February 21, 2023

Explain the role of seekg(), seekp(), tellg(), and tellp() functions in the process of random access in a binary file. How can we open a text file and read from it.

 In C++, seekg(), seekp(), tellg(), and tellp() are functions that allow us to perform random access on a binary file.

seekg() and seekp() are used to set the position of the read/write pointer in a file. seekg() sets the position of the input file pointer (ifstream), while seekp() sets the position of the output file pointer (ofstream). These functions take an offset value and a seek direction as parameters. The seek direction can be one of three values:

ios::beg (beginning of the file)
ios::cur (current position of the pointer)
ios::end (end of the file)

For example, to set the input file pointer to the 10th byte from the beginning of the file, we can use:

ifstream infile("example.bin", ios::binary);
infile.seekg(10, ios::beg);

tellg() and tellp() are used to get the current position of the input and output file pointers, respectively. These functions take no parameters and return the current position of the file pointer. For example, to get the current position of the output file pointer, we can use:

ofstream outfile("example.bin", ios::binary);
int pos = outfile.tellp();

In addition to random access in binary files, we can also read and write text files in C++. To open a text file, we can use the fstream class with the ios::in flag to open the file for input, and the ios::out flag to open the file for output. For example, to open a file named example.txt for reading, we can use:

fstream file("example.txt", ios::in);

To read from the file, we can use the getline() function or the >> operator to extract data from the file. For example, to read a line of text from the file, we can use:

string line;
getline(file, line);

To close the file, we can use the close() function:

file.close();

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget