c++获取ubuntu系统用户名

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);

 

参考资料:

https://blog.csdn.net/qq_31175231/article/details/76461870

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值