获得C程序系统命令输出 [英] Get system command output in C program

查看:124
本文介绍了获得C程序系统命令输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有更好的办法做到这一点?

Is there a better way to do it?

    int numOfCPU;
    system("grep -c ^processor /proc/cpuinfo >> /tmp/cpuinfo");
    FILE *fp = fopen("/tmp/cpuinfo", "r");
    fscanf(fp, "%d", &numOfCPU);
    fclose(fp);
    system("rm /tmp/cpuinfo");

我不希望创建一个中间文件,然后将其删除。

I don't want to create an intermediary file and then remove it.

编辑:

它不是从文件中读取。该命令可以是LS或回声世界,你好

Its not about reading from the file. The command can be "ls" or "echo 'Hello world'"

推荐答案

好吧,我在其他的答案被搞糊涂了。在任何情况下,在这个答案的理念是一样的。您可以直接使用在的popen 功能。

Ok, I was confused in my other answer. In any case, the philosophy in this answer is the same. You can use directly the popen function.

然后,你有这样的事情:

Then you have something like this:

int numOfCPU;
FILE *fp = popen("grep -c ^processor /proc/cpuinfo", "r");

fscanf(fp, "%d", &numOfCPU);
pclose(fp);

我希望这将是有益的。

I hope it will be useful.

这篇关于获得C程序系统命令输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆