C 教材:標準輸入裝置

假設我們將 mycat0.c 編譯了,產生可執行檔 a.out。 但是 a.out 怎麼用呢? 它並不知道怎樣打開一個檔案。 UNIX 的好處是:何必打開一個檔案。 我們可以用 UNIX 的檔案導向功能。按照以下方法試試看 (我們假設黑字是您輸入的,而綠字是 UNIX 的反應)


prompt% a.out < mycat0.c
#include <stdio.h>
 
/*  簡化的 UNIX cat 程式,第一版  (mycat0.c) */
main() {
    int c;
 
    c = getchar();
    while (c != EOF) {
        putchar(c);
        c = getchar();
    }
}
prompt% a.out < mycat0.c >! mycat1.c
prompt% wc mycat0.c mycat1.c
        12        27       182 mycat0.c
        12        27       182 mycat1.c
        24        54       364 total
prompt%

看到沒,利用 UNIX 的檔案導向功能,我們就能實驗自己的程式, 不需要先克服在程式中開檔案的困難。

另外,stdin 也可以直接從鍵盤取得輸入字元。如下:


prompt% a.out
I type a line on terminal
I type a line on terminal
When I hit Enter, stdin takes that line into a.out
When I hit Enter, stdin takes that line into a.out
I can do this to test my program
I can do this to test my program
When I am done, hit Enter and Control-D that means EOF.
When I am done, hit Enter and Control-D that means EOF.
prompt%

我按一個 Enter,使得游標在螢幕的第一格,然後按 Control-D 結束了以上的實驗。 在這個實驗當中,我們看到,每當您按了一次 Enter, UNIX 的介面程式 (shell) 就把那一列文字送去給 a.out 處理。 黑字來自於介面程式對鍵盤輸入的回應 (echo) 功能, 綠字來自於 a.out 的輸出。 用這種方法,可以簡便地測試您的程式是否正確。

[BCC16-C]
單維彰 (2000/04/24) ---
[Prev] [Next] [Up]