gpt4 book ai didi

C snprintf 指定用户主目录

转载 作者:太空宇宙 更新时间:2023-11-04 05:23:44 25 4
gpt4 key购买 nike

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

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

最佳答案

用户控制他的环境 - 所以 HOME 环境变量可能不正确,甚至可能没有设置。

使用getuid()getpwuid()获取系统指定的用户主目录:

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

错误检查留作练习...

关于C snprintf 指定用户主目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43561842/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com