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;
}
#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;
}
argc != 2 時回退 *.*。opendir/readdir/stat;Windows 用 _findfirst/_findnext/_findclose 或 FindFirstFile/FindNextFile。fnmatch() (POSIX) 或 PathMatchSpec (Windows Shlwapi)。getopt_long() (GNU) 或 argp 解析複雜選項 (短/長選項、必選/可選參數)。Boost.Program_options、CLI11、cxxopts 等型別安全庫。命令列參數是 CLI 程式與使用者溝通的橋樑。掌握 argc/argv 基礎解析、路徑正規化、跨平台目錄遍歷,即可編寫專業級的控制台工具 (如 ls、dir、find 等)。