Why fprintf and fscanf do not work with pipe

I wrote a program that creates a pipe, writes a number to a pipe, reads it from a pipe, and prints it to stdout. But it looks like fscanf is seeing an empty thread stream, although I did fflush.

Why doesn't fprintf print anything?

int main() {
    int fd[2];
    pipe(fd);

    FILE* write_file = fdopen(fd[1], "w");
    FILE* read_file = fdopen(fd[0], "r");
    int x = 0;
    fprintf(write_file, "%d", 100);
    fflush(write_file);
    fscanf(read_file, "%d", &x);

    printf("%d\n", x);
}
+4
source share
2 answers

You need to close the end of the letter, not just clear it. Otherwise, it fscanf()does not know if there is more data to read (more digits):

fprintf(write_file, "%d", 100);
fclose(write_file);
fscanf(read_file, "%d", &x);

Alternatively, write a space after the numbers to fscanf()stop looking for more numbers:

fprintf(write_file, "%d ", 100);
fflush(write_file);
fscanf(read_file, "%d", &x);

This should fix the problem.

+4
source

fscanf(read_file,"%d") , -, "%d", , , .., fscanf "" .

, fprintf(write_file, "%d\n", 100); , "" , , fscanf .

+1

Source: https://habr.com/ru/post/1674579/


All Articles