c - 如何使用 C 编程将 UNIX 命令的输出存储到 char 中

标签 c unix

假设这是我的代码:

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/

相关文章:

c - 在 C 中将 float 和整数扫描为字符串

linux - 通俗地说,Mac OS、Ubuntu、Linux、Unix有什么区别?

linux - Linux中write命令的功能

linux - 成熟的 IMAP 库

c - stm32f103c8t6 USART1中断不起作用

c - 使用 Eclipse SPARC bare-C 编译器未找到 "windows.h"

c++ - G++ ABI 兼容性列表

unix - Unix 中的模式转换

c++ - C语言联动typedef & templates

c - 触发 Clang 静态分析器的示例代码