C語言編程中,經常遇到main函數中argc和argv[]這兩個參數。argc是argument count的縮寫,即參數的個數;argv是argument vector的縮寫,即參數列表。argv[0]是程序本身的名字,argv[1]是在命令行中輸入的第一個程序的參數,argv[argc]是NULL,如下所示:
#include "stdio.h" int main (int argc, char *argv[]) { printf ("the argc value is %d \n", argc); int i; for (i = 0; i <= argc; i++){ printf ("the argv[%d] value is %s \n", i, argv[i]); } return 0; } #將上述代碼編譯為test可執行文件,在命令行輸入如下內容 /* ./test arg_1 arg_2 */ #執行結果如下: /* the argc value is 3 the argv[0] value is ./test_c_0 the argv[1] value is arg_1 the argv[2] value is arg_2 the argv[3] value is (null) */
#include "stdio.h" int main (int argc, char *argv[]) { FILE *fp; int c; fp = fopen( argv[1], "r"); while ( (c = fgetc(fp)) != EOF){ printf ("%c", c); } fclose(fp); return 0; }