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

标签 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 之外,是否还可以在进程中创建输出文件夹?

谢谢

最佳答案

如果使用以下代码,您可以去掉 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/

相关文章:

c - 为什么下面的代码会显示一个空白链表?

Java - 文件路径 - 无效的转义序列

c++ - 从函数返回 istream 的正确方法

c++ - CMake 库相邻子目录依赖

c++ - 无法将 Char 转换为 LPWSTR

字符数组不会编译

java - 使用 Java (Swing) 在 JPanel/JFrame 中播放 .wav 声音文件

javascript - JavaScript 中图像的文件路径

c++ - Qt QFrame成为独立窗口

c++ - 我的c++代码。会不会出现内存泄漏?