Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing linux user home directory with fstream

Tags:

c++

linux

I am writing small c++ code to access and edit certain text file in user's home directory. Currently I have following code (this is the relevant part):

bool core(void) {
    std::string autostart_entry = "";
    std::string user_entry = "";
    std::fstream username;
    username.open("username.txt", std::fstream::in);
    std::string location;
    std::string user_name;
    if (username.fail()) {
        username.open("username.txt", std::fstream::out);
        std::cout << "What's your system username? ";
        std::getline(std::cin, user_name);
        username << user_name;
    }
    else
        username >> user_name;
    username.close();
    location = "/home/" + user_name + "/.config/openbox/autostart";
    ...
}

This way, as you can see, I ask user for his username, and append it to the location string, is there any easy way to find user's home directory without asking for user's input? I have tried "~/..." and it doesn't work.

I know I could scan "/etc/passwd" file to find it from there but I am wondering if there is another way.

like image 506
George Dirac Avatar asked Oct 17 '25 03:10

George Dirac


2 Answers

Your best bet here is probably to use the getenv function:

#include <stdlib.h>

const char* homeDir = getenv("HOME");

The $HOME environment variable is generally always set under linux, and it will return you a string to a users home directory (even when it isn't under /home)

EDIT: This will only work for the home directory of the user running the program. If you want the home directory for a different user, you will need to use another approach

EDIT2: Actually, thinking about this for more than 1 second... the above will work, and you should use it first. However, if HOME is not set, you can use getpwuid:

#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>

const char *homedir = getenv("HOME");
if ( homedir == NULL ) {
    homedir = getpwuid(getuid())->pw_dir;
}
like image 68
Signal Eleven Avatar answered Oct 18 '25 16:10

Signal Eleven


If you wanted to go to the home directory, just use chdir("~")

else,

This is a dirty hack but it works

#include <unistd.h>
char currdir[100];
char homedir[100];    
getcwd(currdir); //store the current directory in currdir
chdir("~"); // change the working directory to user's home directory
getcwd(homedir); // get the full address
chdir(currdir);   // go back to the previous directory
like image 39
gokul_uf Avatar answered Oct 18 '25 16:10

gokul_uf