简体   繁体   中英

c program (linux): get command line output to a variable and filter data

i have ac program that runs following command:

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 .

Take a look at 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. 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.

fd_out = popen("sudo grep '' /sys/class/dmi/id/board_*", "r");

Use dup or dup2 to duplicate standart output fd to a file fd

Man dup/dup2

Yes popen is definitely the best choice. Have a look here

       http://www.yolinux.com/TUTORIALS/ForkExecProcesses.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM