Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's wrong with the ifstream seekg

I am trying to do a seek and re-read the data. but the code fails.

The code is

std::ifstream ifs (filename.c_str(), std::ifstream::in | std::ifstream::binary);

std::streampos pos = ifs.tellg();

std::cout <<" Current pos:  " << pos << std::endl;

// read the string
std::string str;
ifs >> str;

std::cout << "str: " << str << std::endl;
std::cout <<" Current pos:  " <<ifs.tellg() << std::endl;

// seek to the old position
ifs.seekg(pos);

std::cout <<" Current pos:  " <<ifs.tellg() << std::endl;

// re-read the string
std::string str2;
ifs >> str2;

std::cout << "str2: (" << str2.size() << ") " <<  str2 << std::endl;
std::cout <<" Current pos:  " <<ifs.tellg() << std::endl;

My input test file is

qwe

The output was

 Current pos:  0
str: qwe
 Current pos:  3
 Current pos:  0
str2: (0)
 Current pos:  -1

Can anyone tell me what's wrong?

like image 220
veda Avatar asked May 03 '13 17:05

veda


People also ask

What are the arguments for Seekg ()?

seekg() is a function in the iostream library that allows you to seek an arbitrary position in a file. It is included in the <fstream> header file and is defined for istream class. It is used in file handling to sets the position of the next character to be extracted from the input stream from a given file.

Why is Ifstream not Opening file C++?

The issue is most likely one of the following: 1) map_2. txt does not exist in the location you specified in your ifstream declaration. 2) You do not have sufficient rights to access the root folder of your C drive.

What is ios :: beg C++?

Three direction used for offset values are: ios_base::beg = from the beginning of the stream's buffer. ios_base::cur = from the current position in the stream's buffer. ios_base::end = from the end of the stream's buffer. Required steps and operations Begin Open a data file for input/output operations.


2 Answers

When ifs >> str; ends because the end of file is reached, it sets the eofbit.

Until C++11, seekg() could not seek away from the end of stream (note: yours actually does, since the output is Current pos: 0, but that's not exactly conformant: it should either fail to seek or it should clear the eofbit and seek).

Either way, to work around that, you can execute ifs.clear(); before ifs.seekg(pos);

like image 152
Cubbi Avatar answered Sep 25 '22 05:09

Cubbi


It looks like in reading the characters it is hitting the EOF and marking that in the stream state. The stream state is not changed when doing the seekg() call and so the next read detectes that the EOF bit is set and returns without reading.

like image 35
diverscuba23 Avatar answered Sep 22 '22 05:09

diverscuba23