The system user name is automatically obtained in the c++ code, so there is no need to change the computer and need to modify the code module that uses the system user name. Application case: write data to the local directory of the system.
The specific implementation code is as follows:
First of all, as a common function, the user name acquisition code can be encapsulated as a function function. To improve code efficiency, it can be defined as an inline function:
#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;
}
};
Second, call the above function in the code to get the user name and generate the local file directory:
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);
Reference materials: