鍵盤輸入不直接送達程序,先經緩衝區暫存:
// echo.c #includeint main() { int ch; while ((ch = getchar()) != EOF) { putchar(ch); } }
運行現象:輸入 hello,按 Enter 後一次性顯示 hello(行緩衝)。若為無緩衝,逐字符即時回顯。
標準流預設:
stdin → 鍵盤,stdout → 螢幕。
可通過 Shell 運算符重定向至文件:
# 輸入重定向:以文件替代鍵盤 ./echo < mywords.txt # 輸出重定向:以文件替代螢幕 ./echo > output.txt # 組合:文件輸入、文件輸出 ./echo < input.txt > output.txt
< 將文件關聯到 stdin,> 將 stdout 關聯到文件。程序完全不知情,仍讀 stdin/寫 stdout,實現解耦。
$ cat mywords.txt hello world $ ./echo < mywords.txt hello world # 程序讀取文件內容並回顯 $ ./echo > out.txt user types: hello Ctrl+D (EOF) $ cat out.txt hello # 輸出導向文件,螢幕無顯示
# 管道:前一程序 stdout 接後一程序 stdin cat input.txt | ./process | sort > result.txt # 錯誤流重定向 ./program 2> error.log # stderr → 文件 ./program > out.txt 2>&1 # stdout+stderr 合併 ./program &> all.log # 簡寫
getchar/putchar 等標準 IO 函數自動適配重定向,無需修改代碼。stdout 行緩衝可能導致日志延遲,關鍵點可用 fflush(stdout) 強制刷新。