LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   mkdir() question (https://www.linuxquestions.org/questions/linux-newbie-8/mkdir-question-4175501810/)

bootfinder 04-15-2014 09:11 AM

mkdir() question
 
I'm using c++ on Ubuntu 12.04

I would like to create a new directory in the home directory, but when I try:
mkdir("~/newdir")

it fails because it doesn't translate "~"

How do I get the absolute path to the home dir?

jpollard 04-15-2014 09:41 AM

Quote:

Originally Posted by bootfinder (Post 5153139)
I'm using c++ on Ubuntu 12.04

I would like to create a new directory in the home directory, but when I try:
mkdir("~/newdir")

it fails because it doesn't translate "~"

How do I get the absolute path to the home dir?

You have to manually translate the HOME environment variable, OR use getpwuid(getuid()) to retrieve the password entry structure (struct passwd), then combine the home directory with the directory you want created - this gives a full path for mkdir.

An alternative to creating a full path - once the home directory has been retrieved you could use chdir(path) to ensure that you are in the right place, then use mkdir with the short name. This is reasonable if you are going to change the working directory to the just created directory for further use.

Of the two choices to determining the home directory, using the getpwuid(getuid()) method is the most reliable. Using the HOME environment variable allows the directory to be created where ever HOME points to, which doesn't HAVE to be the users home directory.

bootfinder 04-15-2014 11:24 AM

thanks for the info.


All times are GMT -5. The time now is 08:14 PM.