c - 使用 C 编程使用 POPEN 将值存储到字符串中

标签 c unix popen

我正在尝试在UNIX下编写C代码来读取文本每一行的第三个单词,并使用POPEN将其存储到字符串中。然而,我的代码在 while 循环内的行给了我一个错误(赋值运算符需要可修改的左值)。这是我的代码:

    int main() {

int license = 0;
char number[100];


FILE *file = popen("grep User results_today.TXT_05012013 > filename", "r");
if ( file != NULL)
{
    char line [128];
    while (fgets(line, sizeof line, file) != NULL)
    {

        number = popen("cut -f3 -d' '", "r");

    }
    fclose (file);

    printf("Hello %s\n", number);
}

我知道这里有一些错误,因为我对 C 还很陌生。但是请帮我纠正它们,谢谢!

最佳答案

FILE *file = popen("grep User results_today.TXT_05012013 > filename", "r");

这将运行一个grep命令来查找User并将输出重定向到文件filename。它将返回一个FILE *,允许您读取此命令的输出,但由于该输出已被重定向,您将不会得到任何内容。

popen("cut -f3 -d' '", "r");

这将运行 cut 命令,因为它没有文件参数,将从 stdin 读取并写入 stdout,该 stdout 可以由 popen 的 FILE * 读取返回,但您没有对其执行任何操作。

您可能想要更多类似的东西:

char line[128];
int number;
FILE *file = popen("grep User results_today.TXT_05012013 | cut -f3 -d' '", "r");
if (file) {
    while (fgets(line, sizeof line, file)) {
        if (sscanf(line, "%d", &number) == 1) {
            printf("It's a number: %d\n", number);
        }
    }
    pclose(file);
}

关于c - 使用 C 编程使用 POPEN 将值存储到字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16452094/

相关文章:

c - Linux中为CFS定义的函数在哪里

c - 这有什么问题?这段代码没有在链表的开头插入元素

你能用 C#define 注释吗?

regex - UNIX 中的子字符串

linux - Cat 命令给出 "No such file or directory"

linux - 指定 Telnet 窗口大小

Python 的 Subprocess.Popen With Shell=True。等到它完成

c - 将结构数组传递给函数?

c - popen 创建一个额外的 sh 进程

python - check_call check_output 调用和子进程模块中的 Popen 方法之间的实际区别是什么?