/* argv.c * * Neal Nelson 2009.10.05 * * Construct a NULL terminated argv array of strings from an input line. */ #include #include #include #define MAXLINE 81 #define MAXARGV 5 /* Prototypes */ char **mkargv(char *buf); main() { char buf[MAXLINE]; char **words, **p; printf("mkArgv: enter words on a line, ^d to quit\n>"); while (fgets(buf, MAXLINE, stdin) != NULL ) { words = mkargv(buf); printf("Contents of argv string array:\n"); for (p = words; *p != NULL; p++) printf(" %s\n",*p); printf(">"); } printf("\n"); } char **mkargv(char *buf) { char *p; char **argv, **argvp; int len; char ws[] = " \n\t\r\f\v"; *argv = (char *)malloc(MAXARGV+1); for (p = buf, argvp=argv; *p != '\0'; ) { p = p + strspn(p,ws); /* skip leading spaces */ len = strcspn(p,ws); if (len != 0) /* get next word */ { *argvp = (char *)malloc(len+1); strncpy(*argvp,p,len); *(*argvp + len) = '\0'; argvp++; p = p+len; } } *(argvp) = NULL; /* end of string array */ return argv; }