在Linux,C ++中获取主目录 [英] Get home directory in Linux, C++
问题描述
我需要一种方法来获得用户主目录在C ++程序运行在Linux上。如果相同的代码在Unix上工作,这将是很好。我不想使用HOME环境值。
I need a way to get user home directory in C++ program running on Linux. If the same code works on Unix, it would be nice. I don't want to use HOME environment value.
AFAIK,根目录是/ root。在我的程序是由root用户运行的情况下,是否可以在此目录中创建一些文件/文件夹?
AFAIK, root home directory is /root. Is it OK to create some files/folders in this directory, in the case my program is running by root user?
推荐答案
需要 getuid
获取当前用户的用户ID,然后 getpwuid
才能获取密码输入目录):
You need getuid
to get the user id of the current user and then getpwuid
to get the password entry (which includes the home directory) of that user:
#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>
struct passwd *pw = getpwuid(getuid());
const char *homedir = pw->pw_dir;
注意:如果你在一个线程应用程序中需要这个,你需要使用 getpwuid_r
。
Note: if you need this in a threaded application, you'll want to use getpwuid_r
instead.
这篇关于在Linux,C ++中获取主目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!