/* argvwords.c - collect argv array from command line words * 2009.09.24 Neal Nelson * * This version actually keeps adding words to the argv line after line * up to the allocated size of the argv array. The program handles multiple * lines and multiple words on a line. End with EOF at the beginning of a line. * * I can probably improve this by scanning the word directly into the * argv array instead of into an intermediate word array. */ #include #include #define MAXLINE 80 #define MAXWORDS 3 char *getArg(char *buf, char *word); void *malloc(); /* should probably use calloc in general */ main() { char buf[MAXLINE]; /* fgets reads only MAXLINE-1 */ char word[MAXLINE+1]; /* add one for zero at end of line */ char *argv[MAXWORDS+1]; /* add one for zero at end of argv array */ char *p; int argc = 0; int i; /* collect command lines until EOF (^d) at begin of line */ while (fgets(buf, MAXLINE, stdin) != NULL) { /* fill up argv */ for (p = buf; (p = getArg(p,word)) != NULL && argc < MAXWORDS; ) { printf (" %s\n", word); /* now put word in argv[argc++] */ argv[argc] = (char *)malloc(strlen(word) + 1); strcpy(argv[argc++],word); } argv[argc] = (char *)0; /* now print out argv */ printf("The words in argv (max %d) ...\n",MAXWORDS); for (i = 0; i < argc; i++) { printf("%s\n",argv[i]); } } } char* getArg(char *buf, char *word) { char *p; int i; for (p = buf; isspace(*p); p++); /* skip leading spaces */ for (i = 0; !isspace(*p) && *p != '\0'; p++) /* get next word */ { word[i++] = *p; } word[i] = '\0'; if (i == 0) return NULL; else return p; }