英文:
Is there a way to make portable file creation?
问题
我正在尝试创建一个C++函数,它在与二进制文件相同的目录中创建名为log.txt
的文件并输出数据。
当我使用ofstream
时,它会在源代码所在的位置创建文件。
如果我将二进制文件移到不同的目录,它就不会创建任何文件。
代码:
ofstream logFile("log.txt");
void print(string msg)
{
if (USING_DEBUG == true) {
cout << "Log: " << msg;
}
logFile << "Log: " << msg;
}
英文:
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;
}
答案1
得分: 2
// 获取可执行文件相对于当前工作目录的目录
// 然后附加“log.txt”并尝试打开该路径下的文件。
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;
// 获取argv[0]的目录(如果有的话)
size_t index = argv0.find_last_of(delimiter);
if (index != std::string::npos)
{
directory = argv0.substr(0, index+1); // +1 包含分隔符
}
logFilePath = directory + "log.txt";
std::cout << "在此处打开日志文件: " << logFilePath << " ";
logFile.open(logFilePath.c_str());
bool success = logFile.is_open();
std::cout << (success ? "成功" : "失败") << "\n";
if (success)
{
logFile << "第一行日志文件\n";
}
return success;
}
int main(int argc, const char** argv)
{
std::ofstream logFile;
openLogFile(argv[0], logFile);
return 0;
}
英文:
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;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论