Created
December 15, 2011 20:15
-
-
Save jasonnyberg/1482660 to your computer and use it in GitHub Desktop.
Foundation for a really, _really_ simple cli.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| int simple_cli(char *filename,int (*parser)(char *cmdline),int count) | |
| { | |
| FILE *ifile = NULL; | |
| char cmdline[MAXCMDLINE]; | |
| int status = 0; | |
| for (cmdline[0]=0;count-- && !status && (ifile = fopen(filename,"r")) != NULL;fclose(ifile),cmdline[0]=0) | |
| while (fgets(cmdline,sizeof(cmdline)-1,ifile) && (!(status=parser(cmdline)))); | |
| return status; | |
| } | |
| #define CLICMD(args,str) ((argc==(args)) && !strcmp(str,argv[0])) | |
| #define CLIINT(x) (strtoul(argv[(x)],NULL,0)) ///< convert strings to int | |
| int parser(char *input) | |
| { | |
| char cmd[1024]; | |
| int s=0; | |
| int argc=0; | |
| char *argv[MAXARGS]; | |
| strcpy(cmd,input); /**< duplicate input (may write to it!) */ | |
| cmd[strcspn(input,"#" NEWLINE)]=0; /**< strip comments */ | |
| if (strlen(cmd)==0) goto done; | |
| else if (!strncmp("SYSTEM ",cmd,7)) system(cmd+7); | |
| else | |
| { | |
| for (argv[argc]=strtok(cmd," \t" NEWLINE);argv[argc] && ++argc<MAXARGS;argv[argc]=strtok(NULL," \t" NEWLINE)); | |
| if (argc==0) ; // blank or comment | |
| else if CLICMD(1,"help") printf(qos_help); | |
| else if CLICMD(2,"o") freopen(argv[1],"a",stdout); | |
| else if CLICMD(1,"QUIT") exit(0); | |
| else printf("Unhandled command: %s (%d arguments)" NEWLINE,argv[0],argc); | |
| } | |
| done: | |
| return s; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment