chdir() to home directory

我是研究僧i 提交于 2019-11-30 22:00:00

问题


I am using the chdir() C function to allow a user to change directory.

The function however, doesn't recognize '~'. Do I need to do any explicit conversion, so chdir doesn't recognize what ~ means? Because mine isn't working. Or am I doing something wrong?


回答1:


Tilde expansion is handled by the shell, not by a system call. You could use getenv() to read the environment variable HOME and then use that as the argument to chdir().

There are system calls to get this information that may be more reliable on an individual system, but they're not completely portable. Look, for example, at getpwuid().




回答2:


Note that POSIX specifies the semantics of tilde expansion:

2.6.1 Tilde Expansion

A "tilde-prefix" consists of an unquoted <tilde> character at the beginning of a word, followed by all of the characters preceding the first unquoted <slash> in the word, or all the characters in the word if there is no <slash>. In an assignment (see XBD Variable Assignment ), multiple tilde-prefixes can be used: at the beginning of the word (that is, following the <equals-sign> of the assignment), following any unquoted <colon>, or both. A tilde-prefix in an assignment is terminated by the first unquoted <colon> or <slash>. If none of the characters in the tilde-prefix are quoted, the characters in the tilde-prefix following the <tilde> are treated as a possible login name from the user database. A portable login name cannot contain characters outside the set given in the description of the LOGNAME environment variable in XBD Other Environment Variables. If the login name is null (that is, the tilde-prefix contains only the tilde), the tilde-prefix is replaced by the value of the variable HOME. If HOME is unset, the results are unspecified. Otherwise, the tilde-prefix shall be replaced by a pathname of the initial working directory associated with the login name obtained using the getpwnam() function as defined in the System Interfaces volume of POSIX.1-2008. If the system does not recognize the login name, the results are undefined.

Note in particular that if my username is me, the results of cd ~ and cd ~me may not be the same! Specifically, the HOME environment variable could be set to a value different from the one returned by getpwnam(). I've been using this technique for (way over 25) years to set my HOME where I want it, and the few programs that don't recognize the difference between cd ~ and cd ~me are some (of the many) banes of my life.



来源:https://stackoverflow.com/questions/9493234/chdir-to-home-directory

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