2017-04-11 25 views
4

我已經編寫了創建管道的程序,向管道寫入數字,從管道讀取數據並將其打印到標準輸出。但它似乎是fscanf看到空管流,雖然我做fflush。爲什麼fprintf和fscanf不能用於管道

爲什麼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); 
} 

回答

4

你必須接近管道的書寫端,不僅刷新它。否則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); 

這應該可以解決您的問題。

+0

誰低估了這個? –

+0

@Ctx幫助!謝謝 :) –

1

fscanf(read_file,"%d")只要從流中讀取數據,因爲它獲取的東西,模式"%d"匹配,即只要沒有空格,非數字等字符被讀取,fscanf「等待」,直到下一個字符的用武之地。

因此,fprintf(write_file, "%d\n", 100);將解決問題,因爲它「終止」寫入管道的數字,以致後續fscanf也將被終止。

相關問題