How to Create File in Directory Relative to the Program itself

May 10, 2009 at 3:20am
I want to create a file, for example, in the same directory as the program, instead of the current direcoty. And I don't want to use stuff like Win API. How can do this? Please give some help.
May 10, 2009 at 4:19am
How did you change the cwd without using OS-dependant stuff?
May 10, 2009 at 4:34am
For example, if I invoke the following "a.exe" using a command line "D:\myprogram\> test\a.exe", the cwd will remain "D:\myprogram\", and create the file "test.txt" in D:\myprogram\ instead of D:\myprogram\test\. And I want the file be created in the same directory as a.exe, wherever I put the program.
1
2
3
4
5
6
7
#include<iostream> 
#include<fstream>
using namespace std;
int main(){
  ofstream a("test.txt");
  a<<"This is a test."<<endl;
}



May 10, 2009 at 5:17am
when the program is executed the current directory changes to the program directory..

so as the program starts, at that time you can store the current directory using GetCurrentDirectory(). now you can use that path everytime even if the current directory changes later.
secondly, if you are working on windows there is a win32 api which tells the path of the current application. i dont remember that.. you can search msdn.


what platform you are working on.. its windows specific.

May 10, 2009 at 6:24am
I want my program to work both Windows and Linux. This is a small CLI program, not a GUI one.

when the program is executed the current directory changes to the program directory..


This is not true to my case. The program I put above will create the file "text.txt" where I invoke it from the command line, but I want it be create in the directory where the binary is.
May 10, 2009 at 7:38am
Use this little trick:
1
2
3
4
int main(int argc, char **argv)
{
    std::string directory = argv[0];//program full path + name of binary file
    directory.erase(directory.find_last_of('\\')+1);//remove name of binary file 
May 10, 2009 at 8:23am
Thank Bazzy, it works!
Topic archived. No new replies allowed.