C程序(Linux): get command line output to a variable and filter data

标签 c command-line variable-assignment

我有一个运行以下命令的 C 程序:

system("sudo grep '' /sys/class/dmi/id/board_*")

并在命令行上给出输出。

我希望将输出存储在 C 程序中的某个变量中,以便我可以过滤 board_serial

最佳答案

看看popen 。下面是一个简单的示例,说明如何使用它来捕获程序输出:

#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;
}

但是,看起来您只是想从文件中读取一些值,对吗?我宁愿打开( fopen() )其中包含值的文件,并将这些值读取到我的 C 程序中的变量中。尝试这样的事情(只是一个简单的例子):

#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;
}

关于C程序(Linux): get command line output to a variable and filter data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12005902/

相关文章:

c - 如何使用strtok将用户输入的单词分隔符分隔为空格

command-line - 在命令行上运行 XQuery

swift - 两次调用 Swift 的 readline 到同一个变量会忽略第二次调用

sql - 在 Sybase SQL 中连接简单字符串的意外结果

c++ - 我可以有条件地选择分配给哪个变量吗?

java - 如何为 Traceroute C 文件创建 JNI 接口(interface)

c - 指针、结构、传递参数、递归

c - 不懂的考试问答

c - C中字符的值

xml - 使用 Windows 命令将非 xml 文件从一个目录复制到另一个目录