Reputation:
I have made a simple scoring system which upon correct answer, stores the numbers of the player in the file. I have used the file name like this :
ofstream outfile ("C:\Aadam\Desktop\Project\Scores.txt",ios::app);
But the problem with this approach is that what if I move the program over to a USB and try to run it in another computer. Now it will look in the directory I specified above but there is no Scores.txt file in there.
What I want to do is to give it a path which is in the project folder. So when I move the program, it shouldn't make a difference because I will move the whole project folder.
Of course I can do this :
ofstream outfile ("Scores.txt",ios::app)
which will always look in the project directory and it will work fine as long as I run the program from the IDE but what if I run the program from the .exe file which is two directories down like
"C:\Aadam\Desktop\Project\bin\Debug\Project.exe"
Now in this case, it can't open the file. So if you know a good way to open files and kindly, Show me the Way.....
Upvotes: 0
Views: 1298
Reputation: 3796
If you run the exe file,ofstream outfile ("Scores.txt",ios::app)
will create a file named "Scores.txt" in the same directory as your program.
Upvotes: 0
Reputation: 106
You can parse argv[0] (it will contain path used to invoke your executable - absolute or relative) and replace executable name in it with "Scores.txt"
Upvotes: 1
Reputation: 61
The easiest way is to pass the file path to program as an argument.
When you run a program from IDE, the project directory is considered as current working directory. If the program is run from the command line, the current working directory is from where the command is being run.
Upvotes: 0