首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C >> C 語言問答

C語言命令行參數完整教程:argc/argv 解析與實戰

     編輯:C 語言問答

掌握 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 中設置運行參數

實戰:參數解析模板

#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)或自行實現簡易解析。

常見錯誤

  1. 原問題代碼 for(i=0;i<arc;i++) → 拼寫錯誤,應為 argc。
  2. 直接訪問 argv[i] 不檢查 i < argc 導致越界。
  3. 修改 argv 字符串內容(某些系統只讀)。
  4. 參數含空格未加引號:test.exe "my file.txt"。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
IDE設置位置
Visual Studio專案屬性 → 偵錯 → 命令參數
VS Codelaunch.json 中 "args": ["hello", "world"]
Code::BlocksProject → Set programs' arguments
Dev-C++執行 → 運行參數
CLionRun/Debug Configuration → Program arguments