首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C 輸入緩衝與重定向詳解:緩衝模式、echo 實戰、文件重定向操作

     編輯:關於C語言

輸入緩衝機制

鍵盤輸入不直接送達程序,先經緩衝區暫存:

  • 行緩衝(標準輸入預設):遇換行符(回車)才將整行送達程序。用戶可用 Backspace 修改,按 Enter 確認提交。
  • 全緩衝(文件輸入典型):緩衝區滿才刷新。
  • 無緩衝:字符即時送達(如某些交互式程序)。

echo 程序演示

// echo.c
#include 
int main() {
    int ch;
    while ((ch = getchar()) != EOF) {
        putchar(ch);
    }
}

運行現象:輸入 hello,按 Enter 後一次性顯示 hello(行緩衝)。若為無緩衝,逐字符即時回顯。

緩衝區作用

  1. 效率:塊傳輸優於逐字符系統調用。
  2. 編輯:提交前可修正輸入錯誤。

重定向

標準流預設:
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          # 簡寫

總結

  • 理解行緩衝/全緩衝/無緩衝差異,選擇適合場景的輸入方式。
  • 重定向是 Unix 哲學「一切皆文件」的體現,程序只需處理標準流。
  • getchar/putchar 等標準 IO 函數自動適配重定向,無需修改代碼。
  • 生產環境注意 stdout 行緩衝可能導致日志延遲,關鍵點可用 fflush(stdout) 強制刷新。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved