#include // for exit #include // for getopt #include // for printf, fprintf, fflush #include // for strtok, memset, memcpy #include // for isdigit // // Purpose: Homework 1, Problem 4 // Usage: hw1-4 [-v] [-{0|1|2}] [-d] < Command // -v verbose mode (include hex output of buf[]) // -0 method 0 (ptr casting) // -1 method 1 (union) // -2 method 2 (variable struct) [ not ANSI-C ] // -d debug mode (output some details) // Comment: // o This is a pedagogic version that illustrates several approaches. // History: // 4 sep 2007 kenw, creation // // --| constants |-- const int MAX_LINE = 50; const int BUFSZ = 100; const char *WHITE = " \t\n"; // white space characters // --| prototypes |-- void getArgs(int argc, char *argv[]); int getTokens(char *cmnd, char *word[], const char *delim); void pkbuf0(int seqnum, int nwords, char *word[]); void pkbuf1(int seqnum, int nwords, char *word[]); void pkbuf2(int seqnum, int nwords, char *word[]); // --| globals |-- int verbose = 0; int method = 0; int debug = 0; // --| defines |-- #define DEBUG(arglst) if (debug) { fprintf arglst; } int main (int argc, char *argv[]) { char cmnd[MAX_LINE]; // command-line char *word[BUFSZ]; // word[k] points to kth word int nwords; // #words in command line int seqnum = 0; int i; getArgs(argc, argv); while (fgets(cmnd, MAX_LINE, stdin) != NULL) { if (cmnd[strlen(cmnd)-1] != '\n') { fprintf(stderr, "*** Ooops, line too long\n"); exit(1); } // for (i=0; (i>> This approach uses a non-ANSI-C feature <<< // void pkbuf2(int seqnum, int nwords, char *word[]) { struct { int seqnum; char *str_ptr[nwords]; char str[BUFSZ-nwords*sizeof(char *)]; } buf; // our buffer char *str_ptr; // ptr to char str int i; str_ptr = &(buf.str[(nwords+1)*sizeof(char *)]); for (i=0; i