C++ – std::ifstream::open() not working


I am developing a prototype for a game, and certain gameplay rules are to be defined in an ini file so that the game designers can tweak the game parameters without requiring help from me in addition to a re-compile. This is what I'm doing currently:

std::ifstream stream;

if (!stream.is_open())
    throw new std::exception("Rule file could not be opened");

// read file contents here


However, my stream never opens succesfully. Diving deep into the STL source during debugging reveals that _getstream() (as defined in stream.c) keeps on returning NULL, but I just can't figure out why this is. Help, anyone?

Edit: Rules.ini is in the same directory as the .exe file.

Best Solution

You are assuming that the working directory is the directory that your executable resides in. That is a bad assumption.

Your executable can be run from any working directory, so it's usually a bad idea to hard-code relative paths in your software.

If you want to be able to access files relative to the location of your executable, you should first determine the path of your executable and create a fully qualified path from that.

You can get the name of your executable by examining the argv[0] parameter passed to main(). Alternatively, if you're on Windows, you can get it with GetModuleFileName() by passing NULL as the first parameter.