②関数のポインタと構造体を使ったプログラム
スポンサーリンク
少し難しいが非常に有用なプログラム。
#include<stdio.h> #include<string.h> int list(void) { printf("func list\n"); return 1; } int show(void) { printf("fanc show\n"); return 1; } int quit(void) { exit(0); } struct command{ char *com_str; int (*com_func)(void); }; struct command coms[]={ {"ls",list},{"dir",list}, {"cat",show},{"type",show}, {"quit",quit},{"exit",quit}, {NULL,NULL} }; int do_command(char *command) { struct command *p; for(p=coms;p->com_str!=NULL;p++){ if(strcmp(p->com_str,command)==0){ return p->com_func(); } } printf("command not found\n"); return 0; } int main() { char command[80]; char *p; while(1) { printf(">"); fgets(command,8,stdin); if((p=strrchr(command,'\n'))!=NULL) *p='\0'; do_command(command); } return 0; }
結果として>というプロンプトの後に好きな文字を打ち込み、
ls,dirならlist。catならshow・・・という感じでコマンド処理を行える。
mainのargvですんでしまうこともある。