12

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

codaddict
  • 445,704
  • 82
  • 492
  • 529
Steveng
  • 1,141
  • 2
  • 11
  • 14

3 Answers3

31

~ 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);
}
codaddict
  • 445,704
  • 82
  • 492
  • 529
  • 10
    -1 for giving example code with a huge buffer overflow issue. You should edit this to use snprintf or check the length of `home` before calling `sprintf`. – R.. GitHub STOP HELPING ICE Sep 01 '10 at 12:49
  • @R..GitHubSTOPHELPINGICE or you could be a programmer who knows the max length possible for a home directory and you know that `MAX` is at least that size or bigger. Those functions are really for people who don't know what they're doing. That's why they didn't exist in the past when people knew how to program. – Deanie Nov 06 '20 at 15:51
  • @Deanie: There is no maximum length on the value of the environment variable `HOME`, even if there is a maximum on what's a valid pathname. The code as written is subject to buffer overflow and writing wrong code like this is exactly the opposite of "knowing how to program". – R.. GitHub STOP HELPING ICE Nov 06 '20 at 16:59
12

~ 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.)

sarnold
  • 102,305
  • 22
  • 181
  • 238
5

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

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358