假设这是我的代码:
int main() {
char *number;
system("grep total myfile > filename");
printf(number);
}
此代码从 myfile 中查找包含“total”的行,并将其输出到名为 filename 的新文件中。我试图将输出直接设置为字符“数字”,而不必从文件名写入/读取。有办法做到这一点吗?
感谢您的帮助!
最佳答案
如果我理解你的标题,你想从执行的命令
中获取输出
,
#include <stdio.h>
#include <stdlib.h>
int main() {
char number[100];
FILE *f = popen("echo 200", "r");
while (fgets(number, 100, f) != NULL) {
printf( "%s\n", number );
}
pclose(f);
return 0;
}
或者您只是想将变量传递到命令中并输出您的变量
#include <stdio.h>
#include <stdlib.h>
int main() {
int n = 100;
char buf[100];
sprintf(buf, "echo %d > filename", n); // format the command
system(buf); // execute
printf("%d\n", n); // print the variable
return 0;
}
关于c - 如何使用 C 编程将 UNIX 命令的输出存储到 char 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16348401/