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

时间:2015-03-03 14:50:25

标签: c++ char filepath

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

之外,还可以在此过程中创建输出文件夹

谢谢

1 个答案:

答案 0 :(得分:1)

如果您使用以下内容,则可以删除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();
}