• Advertisement
Sign in to follow this  

help me understand bug with fstream

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
Advertisement
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 this post


Link to post
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 this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement