/* echowords.c * * Neal Nelson 2009.10.05 * * Echo command and argument words on subsequent lines * Allocate each word in getArg. Shows passing modifiable pointer parameters, * but the allocation of all words on a line should be encapsulated. */ #include #include #include #define MAXLINE 81 /* Prototypes */ char *getArg(char *buf, char **word); main() { char buf[MAXLINE]; char *p, *word; while (fgets(buf, MAXLINE, stdin) != NULL ) { for (p = buf; (p = getArg(p,&word)) != NULL; ) /* last pass is just sp+nl */ { printf (" %s\n", word); } } } /* buf is the incomming string, word is the address of a return string */ char* getArg(char *buf, char **word) { char *p; int len; char ws[] = " \n\t\r\f\v"; p = buf + strspn(buf,ws); /* skip leading spaces */ len = strcspn(p,ws); if (len != 0) /* get next word */ { *word = (char *)malloc(len+1); strncpy(*word,p,len); *(*word+len) = '\0'; return p+len; } else return NULL; }