在linux中编写程序的时候,我们常常会遇到这样一个问题,想要读取linux中某个文件的数值,然后使用脚本命令将数值切割或者查询,最终得到一个返回值,如下
![](https://i-blog.csdnimg.cn/blog_migrate/9a85b137ff1174973431041b09906004.png)
其中,“10.166.0.1”就是我们想要得到的返回值,但是如何才能得到这个返回值呢?
以下是我的一些方法:
一:c++程序
void getNetwork()
{
bool r = true;
string cmd1;//在linux中输入的命令行
string m_network;//返回值
cmd1 = "cat /etc/netplan/01-network-manager-all.yaml | grep gateway4 | cut -d : -f 2";
r = this->SystemCommand(cmd1, m_network);
}
bool SystemCommand(const string &cmd, string &value)
{
char buf[1024] = {0};
FILE *fp = NULL;
if((fp = popen(cmd.c_str(), "r")) != NULL){
while(fgets(buf, 1024, fp) != NULL){
fprintf(stdout, "%s", buf);
}
pclose(fp);
}else{
fprintf(stderr, "popen %s error/n", cmd.c_str());
return false;
}
value = buf;
return true;
}
二:qt程序中
void widget::getNetwork()
{
bool r = true;
QString cmd1;//在linux中输入的命令行
QString m_network;//返回值
cmd1 = "cat /etc/netplan/01-network-manager-all.yaml | grep gateway4 | cut -d : -f 2";
r = this->SystemCommand(cmd1, m_network);
qDebug() << "======================" << m_network << endl;
}
bool widget::SystemCommand(const QString &cmd, QString &value)
{
char buf[1024] = {0};
FILE *fp = NULL;
if((fp = popen(cmd.toUtf8().constData(), "r")) != NULL){
while(fgets(buf, 1024, fp) != NULL){
fprintf(stdout, "%s", buf);
}
pclose(fp);
}else{
fprintf(stderr, "popen %s error/n", cmd.toUtf8().constData());
return false;
}
value = buf;
return true;
}