Std :: ifstream :: open () doesn't work

I am developing a prototype for a game, and some gameplay rules need to be defined in the ini file so that game developers can tweak the game parameters without requiring me to help in addition to recompiling. This is what I am currently doing:

std::ifstream stream;
stream.open("rules.ini");

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

// read file contents here

stream.close();

      

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

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

+1


source to share


3 answers


You are assuming the working directory is the directory where your executable is located. This is a bad assumption.

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



If you want to be able to access files relative to the location of your executable, you must first define the path to your executable and create a full path from it.

You can get the name of your executable by checking the parameter argv[0]

passed to main()

. Also, if you are on Windows, you can get it by GetModuleFileName()

passing NULL as the first parameter.

+7


source


Whether the scope of an open stream is displayed correctly.



"rules.ini" is not a full path, so it must be relative in order for it to refer to it. Or you need to use the full path there.

+2


source


(wild guess here) you are using visual studio. While debugging, your program will look for the project directory for "rules.ini"

However, if you try to execute your program from "myproject / debug / myexe.exe" it should work fine because it will look for "/ debug" for rules.ini

As mentioned, you must specify the full path, because a relative path leads to errors

0


source







All Articles