为什么 grep 给出 "Binary file (standard input) matches"?

Why does grep give "Binary file (standard input) matches"?

#include <stdio.h>

int main()
{
    FILE* cmd = popen("grep Hello", "w");   
    fwrite("Hello\n", 6, 6, cmd);
    fwrite("Hillo\n", 6, 6, cmd);
    fwrite("Hello\n", 6, 6, cmd);   
    pclose(cmd);
}

上面的程序输出:

Binary file (standard input) matches

为什么 grep 会给出消息,如何解决?

fwrite() 后没有 nul 个字节。你的程序有问题的原因是因为你 fwrite()ing 6 个元素,每个元素大小为 6。

您正在尝试写入 36 个字节而不是 6 个字节,有效地访问了字符串末尾以外的字节。绝对未定义的行为。只需要第一个 '[=12=]' 字节。

使用

fwrite("Hello\n", 1, 6, cmd);

或者更简单地说:

fputs("Hello\n", cmd);