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?
            Asked
            
        
        
            Active
            
        
            Viewed 6,857 times
        
    3 Answers
19
            POSIX provides wordexp(3) to perform shell-like expansion, including tilde expansion.
 
    
    
        Cairnarvon
        
- 25,981
- 9
- 51
- 65
19
            
            
        You can you use wordexp example below
#include <stdio.h>
#include <wordexp.h>
int main(int argc, char* argv[]) {
    wordexp_t exp_result;
    wordexp(argv[1], &exp_result, 0);
    printf("%s\n", exp_result.we_wordv[0]);
}
 
    
    
        FDinoff
        
- 30,689
- 5
- 75
- 96
- 
                    8If you use this in a function, you'll want to add `wordfree(&exp_result);` to avoid leaking memory. – ishmael Jan 11 '17 at 05:09
8
            
            
        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.
 
    
    
        Some programmer dude
        
- 400,186
- 35
- 402
- 621
