Search code examples
c++charfilepath

Saving a file in a different place for linux


I am trying to save a file somewhere else than the folder of the exe. I have pieced together this unelegant way:

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

Is there a more elegant way to do this? So that the char-string-char* is not necessary.

Also is it possible to create the output folder in the process apart from mkdir?

Thank you


Solution

  • You can get rid of 3 lines of code if you use the following.

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