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?
The
~shortcut in paths is not something magical at the filesystem level, opening~/GITliterally tries to access~/GIT, i.e: a file namedGITin the~directory. You can verify this by creating~andGITfirst.In the command line,
~is typically resolved by your shell. e.g: in bash:https://www.gnu.org/software/bash/manual/html_node/Tilde-Expansion.html
Therefore, to achieve the same effect, you have to query the
$HOMEenvvar, and replace the usage of leading~/in the path:In addition, on linux, the wordexp function can be used to perform these replacements (~ to current user, ~other_user to home of other user)