C snprintf specify user home directory

巧了我就是萌 提交于 2019-12-18 09:44:42

问题


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, sizeof(filename), "%s_%s.sho", client, id);

回答1:


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).




回答2:


The user controls his environment - so the HOME environment variable may not be correct or it may not even be set.

Use getuid() and getpwuid() to get the user's home directory as specified by your system:

#include <unistd.h>
#include <pwd.h>

struct passwd *pwd = getpwuid( getuid() );

/* need to duplicate the string - we don't know
   what pw_dir points to */
const char *homeDir = strdup( pwd->pw_dir );

Error checking is left as an exercise...




回答3:


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

#include <stdlib.h>
#include <stdio.h>
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.



来源:https://stackoverflow.com/questions/43561842/c-snprintf-specify-user-home-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!