簡體   English   中英

將命令行的output重定向到C中的一個變量

[英]Redirect output of command line to a variable in C

有沒有辦法將返回 integer 作為 output 的命令行的 output 重定向到 C 中的變量?

例如,如果命令是“cmd”,那么有沒有辦法重定向它的 output(整數)並將其存儲在 C 中的變量中? 我嘗試使用 popen 和 fgets 但它似乎只適用於字符。 有什么建議么?

它與 popen 和 fgets 完美配合:

#include <stdio.h>
#include <stdlib.h>

int
main(int argc, char *argv[])
{
    const char *cmd = argc > 1 ? argv[1] : "echo 42";
    char buf[32];
    FILE *fp = popen(cmd, "r");
    if( fp == NULL ){
        perror("popen");
        return 1;
    }
    if( fgets(buf, sizeof buf, fp) == buf ){
        int v = strtol(buf, NULL, 10);
        printf("read: %d\n", v);
    }
    return 0;
}

如果要從標准輸入轉換字符串,可以使用fgets然后使用atoi將輸入轉換為 integer。

如果要轉換命令的 output,假設ls並將命令的 output 存儲到變量,您可以了解forkdup2pipeexec function 系列。

本教程中有關此主題的更多信息: 在 C 中捕獲一個孩子的 output 如果您想保持“高水平”,本教程還提供了一個popen示例。

這是一個使用popen()fscanf()的更簡單的示例:

#include <errno.h>
#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]) {
    FILE *fp = popen("date '+%s'", "r");
    long seconds;
    if (fp == NULL) {
        fprintf(stderr, "popen failed: %s\n", strerror(errno));
        return 1;
    }
    if (fscanf(fp, "%ld", &seconds) == 1) {
        printf("epoch seconds: %ld\n", seconds);
        pclose(fp);
        return 0;
    } else {
        fprintf(stderr, "invalid program output\n");
        pclose(fp);
        return 1;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM