将文件保存在不同的linux位置

Saving a file in a different place for linux

本文关键字:linux 位置 文件 保存 存在      更新时间:2023-10-16

我正在尝试将文件保存到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*。

除了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();
}