本項目實現一個模擬 DOS 內部命令幫助的交互式命令行程序,支持 dir、cd、md、rd、cls、date、time、ren、copy、help 共 10 個命令的語法提示。
YES 顯示所有命令列表)#include <stdio.h>
#include <string.h>
int main() {
char order[15][10] = {"dir","cd","md","rd","cls","date","time","ren","copy","help"};
char input[10], help[10];
int i, j, showHelp = 0;
printf("Do you need help? YES or NO: ");
gets(help);
for (i = 0; i < 5; i++) { // 簡易匹配 YES
if (strcmp(help, "YES") == 0) {
for (i = 0; i < 10; i++) {
for (j = 0; j < 10; j++) putchar(order[i][j]);
putchar('\n');
}
showHelp = 1;
break;
}
}
if (!showHelp) printf("\n請輸入命令:");
for (i = 0; i < 100; i++) {
gets(input);
if (strcmp(input, order[0]) == 0)
printf("dir:查看當前目錄文件/文件夾。\t內部命令\n");
else if (strcmp(input, order[1]) == 0)
printf("cd 目錄名:進入特定目錄。\t內部命令\n");
else if (strcmp(input, order[2]) == 0)
printf("md 目錄名:創建文件夾。\t內部命令\n");
else if (strcmp(input, order[3]) == 0)
printf("rd 目錄名:刪除文件夾。\t內部命令\n");
else if (strcmp(input, order[4]) == 0)
printf("cls:清屏。\t內部命令\n");
else if (strcmp(input, order[5]) == 0)
printf("date:設置/顯示日期。\t內部命令\n");
else if (strcmp(input, order[6]) == 0)
printf("time:設置/顯示系統時間。\t內部命令\n");
else if (strcmp(input, order[7]) == 0)
printf("ren 舊名 新名:重命名。\t內部命令\n");
else if (strcmp(input, order[8]) == 0)
printf("copy 源路徑 目標路徑:複製文件。\t內部命令\n");
else if (strcmp(input, order[9]) == 0)
printf("help:顯示幫助。\t外部命令\n");
else
printf("未知命令。\n");
printf("\n請輸入命令:");
}
return 0;
}
gets() 已棄用(緩衝區溢出風險),應改用 fgets()。system() 或 CreateProcess)。cd test),需加入字符串分割邏輯。熟悉 C 語言字符串處理、流控制與標準庫函數是本項目核心收穫。雖功能簡單,但為理解 Shell 基本原理、命令解析與分發機制打下基礎。後續可嘗試實現真正的微型 Shell(支持管道、重定向、後台任務)。