I'm trying to make a C++ function that creates a file called log.txt in the same directory as the binary and outputs data.
When I use ofstream it creates the file where the source code is.
If I move the binary to a different directory it doesn't create any file.
Code:
ofstream logFile("log.txt");
void print(string msg)
{
if (USING_DEBUG == true) {
cout << "Log: " << msg;
}
logFile << "Log: " << msg;
}
You can parse
argv[0]get the directory of the executable relative to the current working directory at startup. This should be reasonable for what you want. Then append "log.txt" and attempt to open the file at that path.So if argv[0] passed in simply
foo.exeorfoowithout a path qualifier, then you'd open alog.txtfile without an explicit path. If argv[0] is something like../project/bin, then you'd open a log file at../project/log.txt. If it's something likec:\users\selbie\foo.exe, then you'd openc:\users\jselbie\log.txtSome code below that makes an attempt at this.