//linen2.c --- by tsaiwn@csie.nctu.edu.tw
//這版可不必打 小於號 Input redirection; 會 check 有沒輸入檔案名稱
// 就是利用 main(int argc, char**argv) 這種寫法讀取 command line
// tcc linen2.c 或是 gcc linen2.c -o linen2
// linen2 < inputfile.name
// 或以下這樣也可以了:
// linen2 inputfile.name
// linen2 < inputFile.name > outputFile.name
#include <stdio.h>
int main(int argc, char**argv) {
static char buf[999]; // 用 static 就不會佔用 Stack 的空間
int n = 0; // 一開始放 0 這樣加上 1 就是 Line 1
FILE* fp;
//printf(" argc=%d\n", argc);
if(argc <= 1) {
fprintf(stderr, " Read from stdin."
" Enter CTRL_Z to indicate EOF\n");
}
if(argc > 1) { // you had specified a filename
fp = fopen(argv[1], "rt"); // try to open the file
if(fp != 0) { // open OK
fclose(fp); // 有成功, 先關掉檔案
fp = freopen(argv[1], "rt", stdin); // 把 stdin 重新導向
}else{
fprintf(stderr, "? Fail to open %s; read from stdin."
" Enter CTRL_Z to indicate EOF\n", argv[1]);
}
}// if(argc
fgets(buf, sizeof(buf), stdin); // 先讀入一列然後進入 Loop
while(! feof(stdin) ) { // while檔案stdin (鍵盤) 尚未結束
++n;
printf("%5.2d %s", n, buf);
buf[0] = 0; // clear the buffer -- 先把上次讀到的清除 !
fgets(buf, sizeof(buf), stdin); // 在 Loop 內最後再讀入一列
} // while // 注意下列很重要喔, 因輸入檔最後一列可能沒 new Line
if(buf[0] != 0) printf("%5.4d %s", ++n, buf); // 注意 ++n
printf("\n");
if(*buf != 0)fprintf(stderr, "Waring: no newline at end of file\n");
return 0;
} // main 注意要把 Line numbers 去掉
/***
D:\test> path C:\Dev-Cpp\bin;%path%
D:\test> gcc linen2.c -o linen2
D:\test> linen2 linen2.c
D:\test> linen2 < linen2.c
*************/