/* Words are read in and written out in reverse order. Command line syntax is: * * ./a.out N [input-file [output-file]] * * where N is the number of words to read, input-file is the optional name of the input file (defaults to stdin). If * output-file is specified, the input file must also be specified. The output file defaults to stdout if not specified. * * For example: * ./a.out 3 * ./a.out 3 inputfile1 * ./a.out 3 inputfile1 outputfile1 */ #include #include typedef struct node { char *string; struct node *next; } Node; /* Insert the new string into a new node. Treat the linked list like a stack. Note the address of the pointer * to the linked list has been passed in as a parameter. This allows its value to change as required -- it also * means that it must be dereferenced when used. */ void insert( Node **head, char new_string[] ) { Node * ptr; ptr = (Node *) malloc( sizeof(Node) ); if ( ptr == NULL ) { fprintf( stderr, "Error! Could not allocate node\n" ); exit( -1 ); } /* if */ ptr->next = *head; ptr->string = (char *) calloc( strlen( new_string ) + 1, sizeof(char) ); if ( ptr->string == NULL ) { fprintf( stderr, "Error! Could not allocate string\n" ); exit( -1 ); } /* if */ ptr->string = strcpy( ptr->string, new_string ); *head = ptr; } /* insert */ int main( int argc, char (*argv[])[] ) { FILE *in = stdin; /* default to stdin */ FILE *out = stdout; /* default to stdout */ char word[256]; /* handle large words */ Node *root = NULL, *tmp; int NoOfWords = 0; int i; /* Note the "break" statement only occurs in the last case clause. */ switch (argc) { case 4: out = fopen( argv[3], "w" ); if ( out == NULL ) { fprintf( stderr, "Error! Could not open output file %s\n", argv[3] ); exit( -1 ); } /* if */ case 3: in = fopen( argv[2], "r" ); if ( in == NULL ) { fprintf( stderr, "Error! Could not open input file %s\n", argv[2] ); exit( -1 ); } /* if */ case 2: NoOfWords = atoi( argv[1] ); break; default: fprintf( stderr, "Usage:%s N [input-file [output-file]]\n", argv[0] ); exit( -1 ); } /* switch */ /* interactive case */ if ( in == stdin ) { printf( "Enter a list of %d words.\n", NoOfWords ); } /* if */ /* read and insert words into linked list */ for ( i = 0; i < NoOfWords; i += 1 ) { if ( fscanf( in, "%s", word ) == EOF ) break; insert( &root, word ); } /* for */ fprintf( out, "The words in reverse order:\n" ); for ( tmp = root; tmp != NULL; tmp = tmp->next ) { printf( "%s\n", tmp->string ); free( root ); root = tmp->next; } /* for */ } /* main */