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

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

问题描述

有没有更好的方法?

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"或echo 'Hello world'"

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.

然后你有这样的东西:

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

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

希望对你有用.

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

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