用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 10
int 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;
}