【发布时间】:2014-06-09 19:23:17
【问题描述】:
我正在尝试使用system() 命令和模拟器的pid 在我的程序中解析另一个程序(这是一个模拟器)的命令行参数。不幸的是,同时使用文件读取和cat,输出格式不正确,所以我无法真正获取数据。命令行上的cat 显示删除了空格的文件内容,整个字符串粘在一起,使用ifstream,它只显示程序的名称(我猜是第一个参数)。有人有什么想法吗?
参数的格式是这样的:
sudo ./src/yse6 -w -f tracefiles/capacity.3Mbps_400RTT_PER_0.0001.txt -at=eth1 -an=eth0
最终我需要显示与上述格式相同的字符串。
这是我到目前为止所做的:(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
}
}
【问题讨论】:
-
该文件的内容是 NULL 分隔的,而不是空格分隔的...
-
是的,我知道。我猜我应该只玩文件阅读器选项,对吧?
-
将文件的全部内容读入缓冲区(PAGESIZE 字节应该足够了),然后扫描读取的数据为零字节。除了最后一个(你可以告诉你,因为
read()告诉你它实际读取了多少字节),每个零字节之后的字节是下一个字符串的开头...... -
我明白了。感谢您提供的有用信息。我对 C++ 函数不太熟悉,最好能帮我写代码。
标签: c++