c++linuxofstreamtilde-expansion

Open an ofstream with tilde (~) in path name


I have to open some file for writing, and its name contains the tilde sign (~). The following code fails to create the desired text file. If I replace the ~ with /home/oren then everything works fine.

#include <fstream>
#include <string>

const std::string dirname  = "/home/oren/GIT/";
// const std::string dirname  = "~/GIT/";
const std::string filename = "someTextFile";

int main(int argc, char **argv)
{
    std::ofstream log_file(dirname+filename+".txt");
    log_file << "lorem ipsum";
    log_file.close();
}

Is there any way to (easily) handle a file with ~ in its name?


Solution

  • The ~ shortcut in paths is not something magical at the filesystem level, opening ~/GIT literally tries to access ~/GIT, i.e: a file named GIT in the ~ directory. You can verify this by creating ~ and GIT first.

    In the command line, ~ is typically resolved by your shell. e.g: in bash:

    ~ : The value of $HOME

    https://www.gnu.org/software/bash/manual/html_node/Tilde-Expansion.html

    Therefore, to achieve the same effect, you have to query the $HOME envvar, and replace the usage of leading ~/ in the path:

    #include <stdlib.h>
    const char* home = getenv("HOME")
    if (home) { /* replace ~/ with home */ }
    

    In addition, on linux, the wordexp function can be used to perform these replacements (~ to current user, ~other_user to home of other user)