![](/img/trans.png)
[英]c program (linux): get command line output to a variable and filter data
[英]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;
}
這是一個使用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.