使用管道作为流 C
Using a pipe as a stream C
第一次在这里求助
我目前正在用 C 编写一个游戏,对于网络部分,我正在传输一个字符串。为了分析它并取回其中打印的不同 int,我想使用流。因为我在 C 中找不到流,所以我使用 'pipe' 和 fdopen 将其转换为文件流。
一开始我是这样做的:
int main (){
int fdes[2], nombre;
if (pipe(fdes) <0){
perror("Pipe creation");
}
FILE* readfs = fdopen(fdes[0], "r");
FILE* writefs = fdopen(fdes[1], "a");
fprintf(writefs, "10\n");
fscanf(readfs, "%d", &nombre);
printf("%d\n", nombre);
return 0;
}
但它不起作用。
一种实用的方法是使用 write 而不是 fprintf,这是可行的:
int main (){
int fdes[2], nombre;
if (pipe(fdes) <0){
perror("Pipe creation");
}
FILE* readfs = fdopen(fdes[0], "r");
write(fdes[1], "10\n", 3);
fscanf(readfs, "%d", &nombre);
printf("%d\n", nombre);
return 0;
}
我找到了问题的解决方案,但我仍然想了解为什么第一个解决方案不起作用。有什么想法吗?
这是由流缓冲引起的。在调用 fprintf
.
后添加 fflush(writefs);
fprintf(writefs, "10\n");
fflush(writefs);
fscanf(readfs, "%d", &nombre);
第一次在这里求助
我目前正在用 C 编写一个游戏,对于网络部分,我正在传输一个字符串。为了分析它并取回其中打印的不同 int,我想使用流。因为我在 C 中找不到流,所以我使用 'pipe' 和 fdopen 将其转换为文件流。
一开始我是这样做的:
int main (){
int fdes[2], nombre;
if (pipe(fdes) <0){
perror("Pipe creation");
}
FILE* readfs = fdopen(fdes[0], "r");
FILE* writefs = fdopen(fdes[1], "a");
fprintf(writefs, "10\n");
fscanf(readfs, "%d", &nombre);
printf("%d\n", nombre);
return 0;
}
但它不起作用。 一种实用的方法是使用 write 而不是 fprintf,这是可行的:
int main (){
int fdes[2], nombre;
if (pipe(fdes) <0){
perror("Pipe creation");
}
FILE* readfs = fdopen(fdes[0], "r");
write(fdes[1], "10\n", 3);
fscanf(readfs, "%d", &nombre);
printf("%d\n", nombre);
return 0;
}
我找到了问题的解决方案,但我仍然想了解为什么第一个解决方案不起作用。有什么想法吗?
这是由流缓冲引起的。在调用 fprintf
.
fflush(writefs);
fprintf(writefs, "10\n");
fflush(writefs);
fscanf(readfs, "%d", &nombre);