使用fstream访问linux用户主目录 [英] Accessing linux user home directory with fstream
问题描述
我正在编写小的c ++代码来访问和编辑用户主目录中的某些文本文件.目前我有以下代码(这是相关部分):
I am writing small c++ code to access and edit certain text file in user's home directory. Currently I have following code (this is the relevant part):
bool core(void) {
std::string autostart_entry = "";
std::string user_entry = "";
std::fstream username;
username.open("username.txt", std::fstream::in);
std::string location;
std::string user_name;
if (username.fail()) {
username.open("username.txt", std::fstream::out);
std::cout << "What's your system username? ";
std::getline(std::cin, user_name);
username << user_name;
}
else
username >> user_name;
username.close();
location = "/home/" + user_name + "/.config/openbox/autostart";
...
}
这种方式,如您所见,我要求用户提供用户名,并将其附加到位置字符串中,是否有任何简单的方法可以在不要求用户输入的情况下找到用户的主目录?我已经尝试过〜/...",但是它不起作用.
This way, as you can see, I ask user for his username, and append it to the location string, is there any easy way to find user's home directory without asking for user's input? I have tried "~/..." and it doesn't work.
我知道我可以扫描"/etc/passwd"文件从那里找到它,但是我想知道是否还有另一种方法.
I know I could scan "/etc/passwd" file to find it from there but I am wondering if there is another way.
推荐答案
您最好在这里使用getenv函数:
Your best bet here is probably to use the getenv function:
#include <stdlib.h>
const char* homeDir = getenv("HOME");
$ HOME环境变量通常总是在linux下设置,它将使您返回一个字符串到用户的主目录(即使它不在/home下)
The $HOME environment variable is generally always set under linux, and it will return you a string to a users home directory (even when it isn't under /home)
这仅适用于运行该程序的用户的主目录.如果要将主目录用于其他用户,则需要使用另一种方法
This will only work for the home directory of the user running the program. If you want the home directory for a different user, you will need to use another approach
实际上,考虑这个问题的时间超过1秒钟...以上方法将起作用,您应该首先使用它.但是,如果未设置HOME,则可以使用getpwuid:
Actually, thinking about this for more than 1 second... the above will work, and you should use it first. However, if HOME is not set, you can use getpwuid:
#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>
const char *homedir = getenv("HOME");
if ( homedir == NULL ) {
homedir = getpwuid(getuid())->pw_dir;
}
这篇关于使用fstream访问linux用户主目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!