Public Group

# help me understand bug with fstream

This topic is 5200 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

hi, i recently had this strange bug with an ifstream and i figured out the problem, but i dont understand it. this is for my 2d map editor for my tile based RPG. each map can have multiple tilesets. each tileset has a .txt file which contains the data for this tileset (SOLID or NONSOLID for each tile). anyway, for some reason i was getting garbage values when i got to the third tileset data file. it didnt matter which data file, but it was always the third one, and it only happend if there was 3. i only have 3 tilesets, so i couldnt test it with more then 3, but with 1 or 2 this wasnt a problem. anyway, heres what the broken code looked liked:
ifstream file_in;

for(int i = 0; i < tilesets.size(); i++)
{
file_in.open(tilesets.data_path);

int x;

file_in >> x;

file_in.close();
}


now, when tilesets.size was == 1 or 2, it worked fine, but when there was 3 tilesets, on the third go, the x would be a garbage value, like 2483843 or something like that. it wasnt the text file, either, because i tried switching up the order of the tileset, and it was always the last (3rd) tileset who's data was read in bad. anyway, i was going crazy trying everything trying to fix the bug. i got it to work by just opening the file in the contructor instead of with .open(). like this:
for(int i = 0; i < tilesets.size(); i++)
{
ifstream file_in(tilesets.data_path);

int x;

file_in >> x;

file_in.close();
}


does anyone know why the first code wouldnt work but the second code would? thanks for any help

##### Share on other sites
Yes, and it's not a bug. fstream has "good" and "bad" bits, indicating the status of the stream object. When certain events occur, these bits are set. If you close and reopen a stream, even with a different file, you should call std::fstream::clear() before calling std::fstreem::open() again.

##### Share on other sites
interesting. any idea what causes these events? also, while we are on the topic, what happends when i read to (or past) the end of the file?

for example, a txt file looks like this:

1 2

then, in code, i do this:

ifstream file_in("somefile.txt");

int x;
file_in >> x;
file_in >> x;
file_in >> x;

what happends at that third line?

thanks for anymore help

##### Share on other sites
file_in.eof() (IIRC) should become set

##### Share on other sites
std::ios_base::iostate

Each ios-derived class method affects the iostate in specific ways. In the case of your example, iostate::eofbit is set.

1. 1
2. 2
Rutin
20
3. 3
khawk
18
4. 4
A4L
14
5. 5

• 12
• 16
• 26
• 10
• 44
• ### Forum Statistics

• Total Topics
633760
• Total Posts
3013722
×