Steveng
Steveng

Reputation: 1171

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

Upvotes: 12

Views: 5638

Answers (3)

sarnold
sarnold

Reputation: 104080

~ is a shell meta-character, not a kernel-provided 'shortcut'.

See the wordexp(3) or glob(3) man pages if you want to support ~ easily. (They may do much more than you want.)

Upvotes: 12

codaddict
codaddict

Reputation: 455152

~ 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);
}

Upvotes: 31

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798814

~ is usually expanded by the shell. Not using the shell means that you are responsible for expanding it instead.

Upvotes: 5

Related Questions