问题
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 variableHOME
. IfHOME
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 thegetpwnam()
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