掌握 main(int argc, char *argv[]):命令行參數全攻略
標準簽名:
int main(int argc, char *argv[]) // 或 char **argv
argc (argument count):參數個數,**含程序名**,最小為 1。
argv (argument vector):字符串指針數組,argv[0] 為程序路徑/名,argv[1]...argv[argc-1] 為用戶傳入參數。
編譯與運行演示
// test.c
#include <stdio.h>
int main(int argc, char *argv[]) {
printf("argc = %d\n", argc);
for (int i = 0; i < argc; ++i) {
printf("argv[%d] = %s\n", i, argv[i]);
}
return 0;
}
Windows (CMD / PowerShell)
> gcc test.c -o test.exe
> test.exe hello world 123
argc = 4
argv[0] = test.exe
argv[1] = hello
argv[2] = world
argv[3] = 123
Linux / macOS (Terminal)
$ gcc test.c -o test
$ ./test hello world 123
argc = 4
argv[0] = ./test
argv[1] = hello
argv[2] = world
argv[3] = 123
IDE 中設置運行參數
| IDE | 設置位置 |
| Visual Studio | 專案屬性 → 偵錯 → 命令參數 |
| VS Code | launch.json 中 "args": ["hello", "world"] |
| Code::Blocks | Project → Set programs' arguments |
| Dev-C++ | 執行 → 運行參數 |
| CLion | Run/Debug Configuration → Program arguments |
實戰:參數解析模板
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void print_usage(const char *prog) {
printf("Usage: %s [-h] [-v] [-o output] input_file\n", prog);
}
int main(int argc, char *argv[]) {
char *input = NULL, *output = "out.txt";
int verbose = 0;
for (int i = 1; i < argc; ++i) {
if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) {
print_usage(argv[0]); return 0;
} else if (strcmp(argv[i], "-v") == 0) {
verbose = 1;
} else if (strcmp(argv[i], "-o") == 0 && i + 1 < argc) {
output = argv[++i];
} else if (argv[i][0] != '-') { // 位置參數
if (!input) input = argv[i];
else { fprintf(stderr, "多餘輸入文件: %s\n", argv[i]); return 1; }
} else {
fprintf(stderr, "未知選項: %s\n", argv[i]); return 1;
}
}
if (!input) { print_usage(argv[0]); return 1; }
printf("輸入: %s, 輸出: %s, 詳細: %s\n", input, output, verbose ? "是" : "否");
// 實際業務邏輯...
return 0;
}
進階:getopt / getopt_long (POSIX 標準)
#include <unistd.h> // Linux/macOS 原生;Windows 需移植版
int opt;
while ((opt = getopt(argc, argv, "hvo:")) != -1) {
switch (opt) {
case 'h': print_usage(argv[0]); return 0;
case 'v': verbose = 1; break;
case 'o': output = optarg; break;
case '?': return 1;
}
}
// 位置參數在 optind 之後
if (optind < argc) input = argv[optind];
Windows 推薦使用 getopt 移植版(如 https://github.com/skandhurst/getopt-for-visual-studio)或自行實現簡易解析。
常見錯誤
- 原問題代碼
for(i=0;i<arc;i++) → 拼寫錯誤,應為 argc。
- 直接訪問
argv[i] 不檢查 i < argc 導致越界。
- 修改
argv 字符串內容(某些系統只讀)。
- 參數含空格未加引號:
test.exe "my file.txt"。
- 上一篇文章: 高中生自學C語言編程完全指南:從入門到項目實戰
- 下一篇文章: C語言開發環境推薦:從 Turbo C 到現代工具鏈
Copyright ©
程式碼之家 All Rights Reserved