Why mkdir fails to work with tilde (~)?

家住魔仙堡 提交于 2019-12-01 03:35:33

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

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

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!