[英]c program (linux): get command line output to a variable and filter data
i have ac program that runs following command: 我有一个运行以下命令的ac程序:
system("sudo grep '' /sys/class/dmi/id/board_*")
and give output on command line. 并在命令行上输出。
I want the output to be stored in some variable in c program, so that i can filter board_serial
. 我希望输出存储在c程序中的某个变量中,这样我就可以过滤
board_serial
。
Take a look at popen . 看看popen 。 Here is a simple example of how you could use it to capture the program output:
这是一个如何使用它来捕获程序输出的简单示例:
#include<stdio.h>
int main()
{
FILE *p;
p = popen("ls -l", "r");
if(!p) {
fprintf(stderr, "Error opening pipe.\n");
return 1;
}
while(!feof(p)) {
printf("%c", fgetc(p));
}
if (pclose(p) == -1) {
fprintf(stderr," Error!\n");
return 1;
}
return 0;
}
But, it looks like you just want to read some value from a file, am I right? 但是,看起来你只想从文件中读取一些值,对吗? I would prefer to just open (
fopen()
) the files which have the values inside and read those values to variables in my C program. 我更愿意打开(
fopen()
)具有内部值的文件,并将这些值读取到我的C程序中的变量。 Try something like this (just a simple example): 尝试这样的事情(只是一个简单的例子):
#include<stdio.h>
#include<stdlib.h>
#define MAX 100
int main()
{
FILE *fp;
char result[MAX];
int i;
char c;
fp = fopen("/sys/class/dmi/id/board_name", "r");
if(!fp) {
fprintf(stderr, "Error opening file.\n");
return 1;
}
i = 0;
while((c = fgetc(fp)) != EOF) {
result[i] = c;
i++;
}
result[i] = '\0';
printf("%s", result);
i = atoi(result);
printf("%d", i);
if (fclose(fp) == -1) {
fprintf(stderr," Error closing file!\n");
return 1;
}
return 0;
}
Easiest way is to redirect the output to a file and the read that file for parsing the output. 最简单的方法是将输出重定向到文件,然后读取该文件以解析输出。
system("sudo grep '' /sys/class/dmi/id/board_* 1>out.txt 2>err.txt");
fd_out = fopen("out.txt", "r");
fd_err = fopen("err.txt", "r");
Or you can use popen
function. 或者你可以使用
popen
功能。
fd_out = popen("sudo grep '' /sys/class/dmi/id/board_*", "r");
Use dup or dup2 to duplicate standart output fd to a file fd 使用dup或dup2将标准输出fd复制到文件fd
Yes popen is definitely the best choice. 是popen绝对是最好的选择。 Have a look here
看看这里
http://www.yolinux.com/TUTORIALS/ForkExecProcesses.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.