簡單模仿命令列bash功能,模仿命令列bash
用LINUX有一段時間了,一致在bash底下輸入命令但是從來都很疑惑這個bash是如何知道我要輸入的什麼命令,於是用自己所學知識暫時模仿一些bash功能,後續繼續完善功能。
第一次的版本:
/********************************************************************** * Copyright (c)2015,WK Studios * Filename: main.c * Compiler: GCC,VS,VC6.0 win32 * Author:WK * Time: 2015 29 4 ************************************************************************/ #include<stdio.h> #include<stdlib.h>#include<string.h> int main() { char cmd[128]={0}; while(1) { printf("input command:");scanf("%s", cmd); if(0==strcmp(cmd,"help")) { printf("This is help command\n"); } else if(0==(strcmp(cmd,"quit")&&strcmp(cmd,"q"))) { exit(0); } else { printf("command not found\n"); } }}
第二次版本:
/********************************************************************** * Copyright (c)2015,WK Studios * Filename: bash.h * Compiler: GCC,VS,VC6.0 win32 * Author:WK * Time: 2015 29 4 ************************************************************************/ #include<stdio.h>#include<stdlib.h>#include<string.h>#ifndef _BASH_H#define _BASH_H#define CMD_MAX_LEN 128#define DESC_LEN 1024#define CMD_NUM 10int help();int quit();int show(); typedef struct DataNode{ char *cmd; char *desc; int (*handler)();//函數指標 struct DataNode *next;}tDataNode;// t表示typedef定義static tDataNode head[]=//鏈表數組{ {"help","This is help cmd",help,&head[1]}, {"version","Menu program v1.0",NULL,&head[2]}, {"quit","This is quit cmd",quit,NULL}//可以在數組中增加命令,這裡只有幾個命令};tDataNode* find(tDataNode* head,char *cmd); #endif
/********************************************************************** * Copyright (c)2015,WK Studios * Filename: bash.c * Compiler: GCC,VS,VC6.0 win32 * Author:WK * Time: 2015 29 4 ************************************************************************/ #include"bash.h"tDataNode* find (tDataNode *head,char *cmd){if(head==NULL|| cmd==NULL){return NULL; }tDataNode *p=head;while(p!=NULL){if(strcmp(p->cmd,cmd)==0){return p;}p=p->next;}return NULL;}int show(tDataNode *head){tDataNode *p=head;printf("Menu List:\n");while(p!=NULL){printf("%s - %s\n",p->cmd,p->desc);p=p->next;}return 1;}int help()//列印所有命令{ show(head);return 1;}int quit(){exit(0);}
/********************************************************************** * Copyright (c)2015,WK Studios * Filename: main.c * Compiler: GCC,VS,VC6.0 win32 * Author:WK * Time: 2015 29 4 ************************************************************************/ #include"bash,h"int main(){while(1){ char cmd[CMD_MAX_LEN];printf("Input a command number>");scanf("%s",cmd);tDataNode *p=find(head,cmd);if(p==NULL){printf("command not found!\n");continue;}printf("%s - %s\n",p->cmd,p->desc);if(p->handler != NULL)//有點多態的意思調用同一個handler效果不同{ p->handler();//function point}}return 0;}