How to Create File in Directory Relative to the Program itself

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.
How did you change the cwd without using OS-dependant stuff?
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;
}



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.

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.
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 
Thank Bazzy, it works!
Topic archived. No new replies allowed.