我已经编写了创建管道的程序,将一个数字写入管道,从管道读取它并将其打印到标准输出。但似乎是 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/