萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

C 語言命令列參數完整指南:argc/argv 解析、DIR 指令模擬實戰

main 函式簽名與參數含義

int main(int argc, char *argv[])
// 或
int main(int argc, char **argv)
  • argc:參數總數 (含程式名本身),最小值為 1。
  • argv[0]:程式名稱 (含路徑視呼叫方式而定)。
  • argv[1] ... argv[argc-1]:使用者傳入的實際參數。
  • argv[argc] 保證為 NULL (C 標準)。

基礎範例:列印所有參數

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
    printf("程式名稱: %s\n", argv[0]);
    printf("參數個數 (含程式名): %d\n", argc);
    for (int i = 0; i < argc; ++i) {
        printf("argv[%d] = %s\n", i, argv[i]);
    }
    return 0;
}

實戰:模擬 DIR 指令支援盤符、路徑、檔案名

#include <stdio.h>
#include <string.h>
#include <dirent.h>   // POSIX 目錄讀取
#include <sys/stat.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
    char pattern[260] = "*.*";          // 預設模式
    char cwd[260];
    getcwd(cwd, sizeof(cwd));           // 保存目前工作目錄

    // 1. 解析命令列參數
    if (argc == 2) {
        strncpy(pattern, argv[1], sizeof(pattern)-1);
    } else if (argc > 2) {
        fprintf(stderr, "用法: %s [路徑|檔案|盤符]\n", argv[0]);
        return 1;
    }

    // 2. 判斷參數類型並補全模式
    size_t len = strlen(pattern);
    if (len > 0) {
        char last = pattern[len-1];
        if (last == '/' || last == '\\' || last == ':') {
            strncat(pattern, "*.*", sizeof(pattern)-len-1); // 目錄/盤符補全
        }
    }

    // 3. 若為目錄,切換並補全
    struct stat st;
    if (stat(pattern, &st) == 0 && S_ISDIR(st.st_mode)) {
        chdir(pattern);
        getcwd(pattern, sizeof(pattern)); // 取得絕對路徑
        strncat(pattern, "/*.*", sizeof(pattern)-strlen(pattern)-1);
        chdir(cwd); // 恢復原目錄
    }

    // 4. 提取目錄部分用於顯示
    char dirPart[260] = ".";
    char *lastSlash = strrchr(pattern, '/');
    #ifdef _WIN32
    char *lastBack = strrchr(pattern, '\\');
    if (lastBack > lastSlash) lastSlash = lastBack;
    #endif
    if (lastSlash) {
        size_t dlen = lastSlash - pattern + 1;
        strncpy(dirPart, pattern, dlen);
        dirPart[dlen] = '\0';
    }

    // 5. 遍歷列印 (POSIX 版,Windows 可用 _findfirst/_findnext)
    DIR *dp = opendir(dirPart);
    if (!dp) { perror("opendir"); return 1; }

    struct dirent *ep;
    int count = 0, line = 0;
    printf("** 模擬 DIR ** 目錄: %s\n", dirPart);
    while ((ep = readdir(dp))) {
        // 簡易過濾:這裡需自行實作萬用字元比對或用 fnmatch()
        struct stat fst;
        char full[520];
        snprintf(full, sizeof(full), "%s/%s", dirPart, ep->d_name);
        if (stat(full, &fst) == 0) {
            if (S_ISDIR(fst.st_mode))
                printf("    %s\n", ep->d_name);
            else
                printf("  %10ld  %s\n", (long)fst.st_size, ep->d_name);
        }
        if (++line % 23 == 0) { // 分頁
            printf("--- More (按 Enter 繼續) ---");
            getchar();
        }
        ++count;
    }
    closedir(dp);
    printf("總計 %d 個項目\n", count);
    return 0;
}

關鍵技巧總結

  1. 參數預設值:argc != 2 時回退 *.*。
  2. 路徑正規化:處理尾部分隔符、相對/絕對路徑、盤符 (Windows)。
  3. 跨平台目錄讀取:POSIX 用 opendir/readdir/stat;Windows 用 _findfirst/_findnext/_findclose 或 FindFirstFile/FindNextFile。
  4. 萬用字元比對:可用 fnmatch() (POSIX) 或 PathMatchSpec (Windows Shlwapi)。
  5. 分頁顯示:計數換行,暫停等待使用者輸入。

現代化建議

  • 使用 getopt_long() (GNU) 或 argp 解析複雜選項 (短/長選項、必選/可選參數)。
  • C++ 專案優先考慮 Boost.Program_options、CLI11、cxxopts 等型別安全庫。

結語

命令列參數是 CLI 程式與使用者溝通的橋樑。掌握 argc/argv 基礎解析、路徑正規化、跨平台目錄遍歷,即可編寫專業級的控制台工具 (如 ls、dir、find 等)。

copyright © 萬盛學電腦網 all rights reserved