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

2.4k views Asked by At
#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);
}

The program above outputs:

Binary file (standard input) matches

Why does grep give the message, and how to fix it?

2

There are 2 answers

0
chqrlie On BEST ANSWER

You are attempting to write 36 bytes instead of 6, effectively accessing bytes beyond the end of the string. Definitely undefined behaviour. Only the first '\0' byte is expected.

Use

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

Or more simply:

fputs("Hello\n", cmd);
1
Iharob Al Asimi On

There is no nul byte appended by fwrite(). The reason your program has issues is because you are fwrite()ing 6 elements of size 6 each.