tags:

views:

1497

answers:

4

Hi all,

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;
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 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.

+2  A: 

Is the scope of your open stream correct.

"rules.ini" isn't a full path so it has to be relative so what is it relative to. Or do you need to use full path there.

Brody
Sorry, forgot to mention, the file is in the same directory as my .exe file. That should work with the default settings, I think?
Aistina
Aistina, no. it depends on the current working directory. if your app was executed using ../a.out, for example, it would fail
Johannes Schaub - litb
+5  A: 

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.

Shmoopty
A: 

(wild assumption here) you are using visual studio. During debug, your program is going to search the project directory for "rules.ini"

However, if you try executing your program from "myproject/debug/myexe.exe", it should run fine because it is going to search "/debug" for rules.ini

Like its been mentionned you should specify the full path because relative path tend to lead to errors

Eric
A: 

Thanks for the answers. I just tried to call stream.open() with the full filepath as the filename, but it still won't open the stream...

@Whaledawg: It's rules.ini, though I am on Windows so capitalization should not matter much.

Aistina
Is it a permissions problem on the file? If this is windows, and you are specifying the full path as a C-string, are you using double-backslashes?
Mr.Ree