我正在尝试使用命令和模拟器解析程序中的另一个程序(这是一个模拟器)的命令行参数.不幸的是,使用文件读取和输出都没有很好的格式化,所以我无法真正获得数据.在命令行显示删除空格的文件内容,整个字符串粘在一起,用,那只能说明该程序的名称(第一个参数我猜).任何人都有任何想法?system()pidcatcatifstream
参数的格式如下:
sudo ./src/yse6 -w -f tracefiles/capacity.3Mbps_400RTT_PER_0.0001.txt -at=eth1 -an=eth0
Run Code Online (Sandbox Code Playgroud)
最后我需要显示与上面格式化相同的字符串.
这是我到目前为止已经完成:(ExecCommand()得到一个命令,它运行在命令行并返回结果string.Secondary()尝试使用文件阅读器来获得文件内容.)
std::string ExeCommand(const char* cmd) {
FILE* pipe = popen(cmd, "r");
if (!pipe) return "ERROR";
char buffer[128];
std::string result = "";
while(!feof(pipe)) {
if(fgets(buffer, 128, pipe) != NULL)
result += buffer;
}
pclose(pipe);
return result;
}
void secondary(string addr){
ifstream file(addr.c_str(),ios::in);
if (file.good())
{
string str;
while(getline(file, str))
{
istringstream ss(str);
cout<<str<<endl;
char num[50];
while(ss >> num)
{
cout<<num;
}
}
}else{
cout<<"no file exists."<<endl;
}
}
int main (int argc, char* argv[])
{
if ((string) argv[1] == "-q") {
string pid=ExeCommand("ps -A | grep 'yse6' | awk '{print $1}'");
if(pid==""){
cout<<"No YSE emulator is running."<<endl;
}else{
pid=pid.substr(0,pid.size()-1);
cout<<pid<<endl;
string addr="cat /usr/bin/strings /proc/"+pid+"/cmdline";
cout<<addr<<endl;
// secondary(addr);
const char * c = addr.c_str();
string config=ExeCommand(c);
//get the config
cout << config<<endl;
}//end of else
}
}
Run Code Online (Sandbox Code Playgroud)
像这样的东西,但有更多的错误检查,应该是一个良好的开端(这比C++更多C,除了cout一点):
const int BUFSIZE = 4096; // should really get PAGESIZE or something instead...
unsigned char buffer[BUFSIZE]; // dynamic allocation rather than stack/global would be better
int fd = open("/proc/self/cmdline", O_RDONLY);
int nbytesread = read(fd, buffer, BUFSIZE);
unsigned char *end = buffer + nbytesread;
for (unsigned char *p = buffer; p < end; /**/)
{ cout << p << endl;
while (*p++); // skip until start of next 0-terminated section
}
close(fd);
Run Code Online (Sandbox Code Playgroud)
特别是,open()和read()应检查错误的条件,但我还没有这部分...这也可能会失败,在极端情况下,你的命令行> 4096个字符长,或者一些其他原因,read()不读一次调用中的文件,在当前的/proc实现中不应该发生,但并不总是保证...