C snprintf specify user home directory

前端 未结 3 749
清歌不尽
清歌不尽 2020-12-22 10:11

I use snprintf to write formatted data to disk, but I have one problem, how do I save it to the user\'s home directory?

 snprintf(filename, siz         


        
3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-22 10:36

    Use getenv(3) to query the value of the HOME environment variable. For example, this prints my home directory:

    #include 
    #include 
    int main(void) {
        printf("%s\n", getenv("HOME"));
        return 0;
    }
    

    You can set your variable filename to the return value, and then write whatever data you want there.

    This should work on any Unix-like system, including Linux, macOS, BSD, and probably many more.

提交回复
热议问题