How do I achieve tilde expansion in C?

前端 未结 3 1880
感动是毒
感动是毒 2021-01-04 01:48

chdir(\"~/\") doesn\'t seem to work. Am I expected to look at the string and substitute tilde by hand, or is there some better way?

3条回答
  •  耶瑟儿~
    2021-01-04 02:19

    The tilde in a path is a shell specific thing. What you can do see if the first character is a tilde and a slash (or a tilde end end of the string), then replace the tilde with the value of the environment variable HOME (which you can get from getenv).

    If the second character is not a slash, it's most likely in the form of ~user/path. Then you have to extract the user-name and use e.g. getpwnam to get the password entry of the user, which contains that users home directory.

提交回复
热议问题