Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why mkdir fails to work with tilde (~)?

When I write

mkdir("~/folder1" , 0777);

in linux, it failed to create a directory. If I replace the ~ with the expanded home directory, it works fine. What is the problem with using ~ ?

Thanks

like image 978
Steveng Avatar asked Sep 01 '10 09:09

Steveng


People also ask

Can mkdir fail?

The mkdir() function shall fail if: [EACCES] Search permission is denied on a component of the path prefix, or write permission is denied on the parent directory of the directory to be created.

What does tilde do in bash?

In this article, we learned the meaning of the ~ character and how tilde expansion works in Bash. We use it to refer to a user's home directory, current and previous working directories, and even entries on the directory stack.


1 Answers

~ is known only to the shell and not to the mkdir system call.

But if you try:

system("mkdir ~/foo");

this works as the "mkdir ~/foo" is passed to a shell and shell expands ~ to $HOME

If you want to make use of the $HOME with mkdir, you can make use of the getenv function as:

char path[MAX];
char *home = getenv ("HOME");
if (home != NULL) {
        snprintf(path, sizeof(path), "%s/new_dir", home);
        // now use path in mkdir
        mkdir(path, PERM);
}
like image 101
codaddict Avatar answered Oct 07 '22 03:10

codaddict