Home > Software engineering >  Opening a file in home directory
Opening a file in home directory

Time:11-26

Say you have a program you run, and it has the following lines of code:

#include <fstream>
using std::fstream;

int main() {
     fstream someFile;
     someFile.open("~/someFile");

     if(!someFile.is_open()) {
          // Make the file
     }
}

I'm trying to open a file in the home directory (i.e. "~" on Unix devices). How could this be done? What I'm doing right now doesn't seem to work. Additionally, how can I make the file if it doesn't exist yet?

Note that this program can run from anywhere; not just home, but I need it to look for a file in the home directory.

CodePudding user response:

open has a second parameter: openmode, so you may want something like

someFile.open ("somefile", std::fstream::out | std::fstream::app);

if you want to append.

For the home directory you can check HOME environment variable and getpwuid:

const char *homedir;

if ((homedir = getenv("HOME")) == NULL) {
    homedir = getpwuid(getuid())->pw_dir;
}
  • Related