- 註冊時間
- 2012-7-22
- 最後登錄
- 2012-7-28
- 主題
- 查看
- 積分
- 94
- 閱讀權限
- 30
- 文章
- 59
- 相冊
- 0
- 日誌
- 0
 
狀態︰
離線
|
主程式 main() 有兩個引數 argc 與 argv,即函數 main 標題的定義為
main( int argc, char *argv[] )
其作用是 執行該檔 及 所相隨的 option。
如果將一程式 file.c 編譯完之後, 產生一 執行檔 file.exe。 當執行 file.exe 如
c:> file option1 option2 option3
則執行 file.exe 時, argc 的值為 4, argv 則 含 4 個字串,即
argv[0]="file"、 argv[1]="option1"、 argv[2]="option2"、 argv[3]="option3"。
如此一來 程式的設計, 可以有 較多的彈性。
例如, 於 DOS 下的指令 dir,我們就 可以有 多種選擇,例如
dir *.*/w
dir *.c/w /p
等。
檔案的 輸入 與 輸出 亦可不需 hardcoding, 於例 3 中, 將檔案名稱 file1.txt 及 file2.txt 放在程式裡面, 如此一來,檔案一改 程式 也要 跟著改,程式 變的 非常 沒有彈性。 因此,程式改成 例 4,就比較 有彈性。
例 4: 試設計一程式,其檔名為 copyFile.c, 如同 例 3, 用來 copy 一檔案 至 另一檔案。
#include <stdio.h>
void main(int argc, char *argv[])
{ char c;
int toScreen = 1;
FILE *fpin, *fpout;
if(argc < 2 || argc > 3)
{ printf("The correct format is: copyFile file1 file2\n");
exit(1);
}
fpin = fopen(argv[1], "r");
if( !fpin )
{ printf("The file: %s is not found!\n", argv[1]);
return;
}
if(argc == 3)
{ fpout = fopen(argv[2], "w");
if( !fpout )
{ printf("The file: %s is not found, or no available space!\n", argv[2]);
return;
}
toScreen = 0;
}
while( (c=getc(fpin)) != EOF)
{ if( toScreen )
putchar(c);
else
putc(c, fpout);
}
fclose(fpin);
if( !toScreen)
fclose(fpout);
|
|