2015-10-16 96 views
-2

該程序讀取文件的內容並通過管道發送它們。我在讀取子進程中的管道時遇到問題。我的輸出文件中的內容是方塊字符。我想我必須將c從一個地址改爲一個值?從C中的管道讀取字符

if (pid > 0) { /* parent */ 
/* close the end of the pipe we do not need */ 
close(pfd[0]); 

/* read from the input file and write to the pipe */ 
while ((c = getc(from)) != EOF){ 
    if (flipping){ 
     c = flipChar(c); 
     write(pfd[1],&c, 1); 
    } 
    else 
     write(pfd[1],&c, 1); 

} 

    fclose(from); 
    close(pfd[1]); 

    wait(NULL); 
} 
else{ /* child process */ 

     close(pfd[1]); 

     while (c = read(pfd[0],&c,1)) 
     { 
     /* change c from a address to value?? */ 
     putc(c, destfile); 
     } 

     fclose(destfile); 
     close(pfd[0]); 
} 

return 0; 
}   
+0

任何錯誤輸出? 「有麻煩」的性質是什麼? –

回答

0

read()返回讀取的字符數。所以你執行read(pfd[0], &c, 1),它在c中存儲一個字符,然後立即用值1覆蓋該字符(因爲你從管道中讀取單個字符)。

+0

所以read()函數是我不應該使用的東西?我應該在代碼中更改哪些內容,以便從父進程傳遞的字符在子進程中被拾取? – NuClArPeNgUiN

+0

你正在從你的管道中拾取角色。你正在調用'read()',並且你正在'c'中存儲一些東西。這很好。但是在完成之後,你繼續覆蓋剛剛存儲的字符,因爲你也正在使用由'read()'生成的返回碼(它與您從管道中讀取的字符不相同)也變成'c'。 –

+0

換句話說:爲什麼你期望'read()'從管道返回下一個字符,假設你傳遞了一個緩衝區來存儲事物?如果你想一次讀2個或多個字符,你期望'read()'的返回值是什麼? –