我正在尝试将文件保存在 exe 文件夹之外的其他位置。我用这种不雅的方式拼凑了起来:
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>
#include <unistd.h>
using namespace std;
int main() {
//getting current path of the executable
char executable_path[256];
getcwd(executable_path, 255);
//unelegant back and forth conversion to add a different location
string file_loction_as_string;
file_loction_as_string = executable_path;
file_loction_as_string += "/output_files/hello_world.txt"; //folder has to exist
char *file_loction_as_char = const_cast<char*>(file_loction_as_string.c_str());
// creating, writing, closing file
ofstream output_file(file_loction_as_char);
output_file << "hello world!";
output_file.close();
}
有没有更优雅的方法来做到这一点?因此不需要 char-string-char*。
除了 mkdir
之外,是否还可以在进程中创建输出文件夹?
谢谢
最佳答案
如果使用以下代码,您可以去掉 3 行代码。
int main()
{
//getting current path of the executable
char executable_path[256];
getcwd(executable_path, 255);
//unelegant back and forth conversion to add a different location
string file_loction_as_string = string(executable_path) + "/output_files/hello_world.txt";
// creating, writing, closing file
ofstream output_file(file_loction_as_string.c_str());
output_file << "hello world!";
output_file.close();
}
关于c++ - 将文件保存在 linux 的不同位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28834812/