9

Is here any possibility to use paths beginning with "~" in c++ codes in linux? For example this code is not working correctly:

#include <iostream>
#include <fstream>
using namespace std;

int main () 
{
  ofstream myfile;
  myfile.open ("~/example.txt");
  myfile << "Text in file .\n";
  myfile.close();
  return 0;
}
  • 1
    Do you have a directory in the working directory called `~`? Opening a filed in a directory that doesn't exist won't automatically create a directory for you. E.g. `mkdir \~` . – CB Bailey Nov 05 '15 at 12:11

1 Answers1

12

I guess you are on a Linux or POSIX system, with an interactive shell understanding ~ (e.g. bash)

Actually, files paths starting with ~ almost never happens (you could create such a directory with mkdir '~'in the shell, but that would be perverse). Remember that your shell is globbing arguments, so your shell (not your program!) is replacing ~ with e.g. /home/martin when you type myprogram ~/example.txt as a command in your terminal. See glob(7). You probably want to use glob(3) or wordexp(3) inside your C++ program (but you need to do so only if the "~/example.txt" string comes from some data - e.g. some configuration file, some user input, etc...)

Sometimes, you might simply use getenv(3) to get the home directory (or getpwuid(3) with getuid(2)). Perhaps you might do

std::string home=getenv("HOME");
std::string path= home+"/example.txt";
ofstream myfile(path);

If you are serious, you should check that getenv("HOME") does not return NULL. In practice, that is unlikely to happen.

See also this.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547