/* argv.c * * Neal Nelson 2009.10.16 * * Construct a NULL terminated argv array of strings from an input line. * BUGS: The mkargv mallocs but does not free, so the main loop is * leaking memory on every call to mkargv. It now seems to me better * to just hard-allocate fixed space in the main shell loop for * the argv string array. */ #include #include #include #define MAXLINE 81 #define MAXARGV 5 /* Prototypes */ char **mkargv(char *buf); main() { char buf[MAXLINE]; char **argv; int i; printf("mkArgv: enter words on a line, ^d to quit\n>"); while (fgets(buf, MAXLINE, stdin) != NULL ) { argv = mkargv(buf); for (i=0; argv[i] != (char *)NULL; i++) printf(" %s\n",argv[i]); printf(">"); } printf("\n"); } char **mkargv(char *buf) { char *p; /* p points to progress in buf */ char **argv; int len, argc; char ws[] = " \n\t\r\f\v"; argv = (char **)calloc(MAXARGV+1, sizeof(char *)); p = buf + strspn(buf,ws); /* skip leading whitespace */ for (argc = 0; *p != '\0' && argc < MAXARGV; argc++) { len = strcspn(p,ws); /* get next word */ argv[argc] = (char *)calloc(len+1,sizeof(char)); strncpy(argv[argc],p,len); *(argv[argc] + len) = '\0'; /* string terminator */ p = p+len; /* point past this word */ p = p + strspn(p,ws); /* skip trailing whitespace */ } argv[argc] = (char *)NULL; /* end of string array */ return argv; }