Reputation: 38
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;
}
Upvotes: 0
Views: 144
Reputation: 104569
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.exe
or foo
without a path qualifier, then you'd open a log.txt
file 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 like c:\users\selbie\foo.exe
, then you'd open c:\users\jselbie\log.txt
Some code below that makes an attempt at this.
bool openLogFile(const std::string& argv0, std::ofstream& logFile)
{
#if WIN32 || _WIN32
const char delimiter = '\\';
#else
const char delimiter = '/';
#endif
std::string directory;
std::string logFilePath;
// get the directory of argv[0], if any
size_t index = argv0.find_last_of(delimiter);
if (index != std::string::npos)
{
directory = argv0.substr(0, index+1); // +1 to include the delimiter
}
logFilePath = directory + "log.txt";
std::cout << "opening log file at: " << logFilePath << " ";
logFile.open(logFilePath.c_str());
bool success = logFile.is_open();
std::cout << (success ? "succeeded" : "failed") << "\n";
if (success)
{
logFile << "First log file line\n";
}
return success;
}
int main(int argc, const char** argv)
{
std::ofstream logFile;
openLogFile(argv[0], logFile);
return 0;
}
Upvotes: 2