2015-04-03 60 views
1

我第一次在這裏尋求幫助。使用管道作爲流C

我目前正在用C語言編寫一個遊戲,併爲網絡部分傳輸一個字符串。爲了分析這個並獲取打印在其中的不同int,我想使用一個流。由於我在C中找不到任何流,因此我使用'pipe'和fdopen將其轉換爲File流。

我是在第一次做這樣的:

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; 
} 

但它不工作。 的功能的方法是使用寫的,而不是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; 
} 

我找到了解決我的問題,但我還是想知道爲什麼第一個解決方案是行不通的。任何想法 ?

回答

1

這是流緩衝造成的。在致電fprintf後添加fflush(writefs);

fprintf(writefs, "10\n"); 
fflush(writefs); 
fscanf(readfs, "%d", &nombre); 
+0

謝謝,我知道緩衝,但我確信'\ n'激活緩衝區刷新。 此解決方案正在運行,thx :) – 2015-04-04 12:16:32