C snprintf specify user home directory

前端 未结 3 744
清歌不尽
清歌不尽 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:59

    On Linux and POSIX systems the home directory is often from the HOME environment variable. So you might code

    snprintf(filename, sizeof(filename), "%s/%s_%s.sho", 
             getenv("HOME"), client, id);
    

    Pedantically the getenv(3) could fail (or be wrong). But that rarely happens. See environ(7).

    (You might check, and or use getpwuid(3) with getuid(2)...)

    With setuid executables things could become interestingly complex. You would need to define more precisely what the home is, and code appropriately (this is left as an exercise).

提交回复
热议问题