为什么 fprintf 和 fscanf 不适用于管道 [英] Why fprintf and fscanf does not work with pipe

查看:26
本文介绍了为什么 fprintf 和 fscanf 不适用于管道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写了创建管道的程序,将一个数字写入管道,从管道中读取它并将其打印到标准输出.不过好像是fscanf看到了空管道流,虽然我做了fflush.

I have written the program which creates pipe, write a number to pipe, read it from pipe and print it to stdout. But it seems to be that fscanf see empty pipe stream, although I made fflush.

为什么 fprintf 不打印任何东西?

Why fprintf does not 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);
}

推荐答案

你必须关闭管道的写入端,而不仅仅是冲洗它.否则 fscanf() 不知道是否还有数据要读取(更多位数):

You have to close the writing end of the pipe, not only flush it. Otherwise the fscanf() doesn't know, if there is still data to read (more digits):

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

或者,在数字后写一个空格,使 fscanf() 停止寻找更多数字:

Alternatively, write a blank after the digits to make fscanf() stop looking for more digits:

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

这应该都能解决您的问题.

This should both fix your issue.

这篇关于为什么 fprintf 和 fscanf 不适用于管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆