C snprintf指定用户主目录 [英] C snprintf specify user home directory

查看:125
本文介绍了C snprintf指定用户主目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用snprintf将格式化的数据写入磁盘,但是有一个问题,如何将其保存到用户的主目录?

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

推荐答案

在Linux和POSIX系统上,主目录通常是环境变量中的 .所以你可以编码

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

getenv(3)可能会失败(或是错误的).但这很少发生.参见 environ(7).

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

(您可以检查和/或使用 getpwuid(3) getuid(2) ...)

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

使用 setuid 可执行文件,事情可能会变得非常有趣.您将需要更精确地定义房屋是什么,并进行适当的编码(这留作练习).

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

这篇关于C snprintf指定用户主目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆