c - 为什么 fprintf 和 fscanf 不适用于管道

标签 c unix

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

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

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() 不知道,如果还有数据要读取(更多数字):

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

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

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

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

关于c - 为什么 fprintf 和 fscanf 不适用于管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43349397/

相关文章:

unix - 解析一个字符串的 1000 个脚本的最佳方法?

无法想象无限循环的情况

c++ - 优化数学表达式

linux - 当没有输入参数时,如何使用 getopts 来避免运行脚本?

linux - awk:根据给定列的前 3 个不同值选择行

c - 终端背景颜色并不总是使用 "\033[0m"正确重置

c - 给定条件下的逆模运算符

c++ - 在 typedef 上使用 sizeof 而不是局部变量

使用 dup2 创建管道

unix - 安装memcached - 找不到libevent