ROS系列——Ubuntu下通过C++实现ls、mkdir、dmesg等终端命令的方法
说明
这里主要使用的是std::system函数
C++ 实现该功能的源码
#include <iostream>
#include <fstream>
#include <string>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include "ros/ros.h"
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <vector>
using namespace std;
void ReadFile(const std::string &file_name)
{
std::ifstream fp(file_name);
if(!fp.is_open())
{
std::cout<<"Open Error......"<<std::endl;
}
std::string read_str;
std::cout<<"======================================="<<read_str<<std::endl;
while(std::getline(fp,read_str))
{
std::cout<<"Read File: "<<read_str<<std::endl;
}
std::cout<<"======================================="<<read_str<<std::endl;
fp.close();
}
int main(int argc, char *argv[])
{
ros::init(argc, argv, "get_cmd_result");
ros::NodeHandle nh;
ros::Rate looprate(10);
string save_path;
string open_path;
string mycmd;
bool is_open;
nh.param<string>("mycmd",mycmd,"ls");
nh.param<string>("save_path",save_path,"/home/test.txt");
nh.param<bool>("is_open",is_open,"false");
nh.param<string>("open_path",open_path,"/home/test.txt");
if(!is_open)
{
string tmpstr="";
tmpstr=mycmd+">"+save_path;
std::system(tmpstr.data());
ReadFile(save_path);
}
else
{
//实现了其它功能
}
return 0;
}