在Linux中获取主目录 [英] Get home directory in Linux

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

问题描述

我需要一种在Linux上运行的C ++程序中获取用户主目录的方法.如果相同的代码可以在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中获取主目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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