c++代码中自动获取系统用户名,因此不必再纠结换电脑后需要再修改用到系统用户名的代码模块了,应用案例:将数据写到系统本地目录下。
具体实现代码如下:
首先,作为一个常用功能,可以将获取用户名代码封装为功能函数,为提高代码效率,可定义为inline函数:
#include <unistd.h>
#include <pwd.h>
class Utility
{
public:
inline std::string getUserName(){
struct passwd* pwd;
uid_t userid;
userid = getuid();
pwd = getpwuid(userid);
// cout<<pwd->pw_name<<endl;
return pwd->pw_name;
}
};
其次,在代码中调用上述函数,获取用户名,生成本地文件目录:
bool Bbx::saveLog(std_srvs::Empty::Request &request, std_srvs::Empty::Response &response)
{
ROS_WARN("save data to TXT ......");
// //! get system user name.
// struct passwd* pwd;
// uid_t userid;
// userid = getuid();
// pwd = getpwuid(userid);
// cout<<pwd->pw_name<<endl;
std::string username = utility.getUserName();
// ****** 保存数据到本地txt文件
// estimates
// std::string filePath = "/home/chenlu/est.txt";
std::string filePath = "/home/"+username+"/est.txt";
std::ofstream outFile1;
outFile1.open(filePath, std::ios::app|std::ios::out);
outFile1<<std::fixed;
outFile1.precision(3);
if(outFile1.bad()){
cout<<"cannot create file: "<<filePath<<endl;
return 1;
}
for(int i=0; i<PCL::bbxEst.size(); i++){
outFile1<<PCL::bbxEst[i][0]<<"\t"<<PCL::bbxEst[i][1]<<"\t"<<PCL::bbxEst[i][2]<<endl;
}
outFile1.close();
// std::cout<<"estimates saved in file = "<<filePath<<endl;
ROS_WARN_STREAM("estimates saved in file = "<<filePath);
参考资料: