#include<stdio.h> #include<string.h> #include<stdlib.h> #define MAX_WORD 16 /* function prototype */ unsigned char GetWord(FILE *wordFile, char *word); int main(void) { struct node { char word[MAX_WORD]; struct node *next; }; struct node *list; /* points to the first word in the list */ struct node *end; /* points to the last word in the list */ struct node *tmpPtr; /* used to scan through the list */ char tempWord[MAX_WORD * 4]; FILE *fptr; /* open the file */ if ( (fptr = fopen("words.txt", "r")) == NULL ) { printf("Unable to open filen"); return 1; } /* get the first word from the user and start the list */ GetWord(fptr, tempWord); list = (struct node *)malloc(sizeof(struct node)); strcpy(list->word, tempWord); list->next = NULL; end = list; /* read more words and store in the linked list */ while (GetWord(fptr, tempWord)) { end->next = (struct node *)malloc(sizeof(struct node)); end = end->next; strcpy(end->word, tempWord); end->next = NULL; } fclose(fptr); /* print out the words as entered by user */ end = list; printf("%sn", end->word); while (end->next != NULL) { end = end->next; printf("%sn", end->word); } printf("nn"); /* print words in reverse and delete */ while (list != NULL) { if (end == list) /* only one node left */ { printf("%sn", list->word); free(list); list = NULL; } else { tmpPtr = list; while (tmpPtr->next != end) tmpPtr = tmpPtr->next; printf("%sn", end->word); tmpPtr->next = NULL; free(end); end = tmpPtr; } } return 0; } /* GetWord() Gets a word from the file and checks it to see that it does not exceed the maximum allowable length Input(s): a pointer to the file a pointer to the array where the word is to be placed Output(s): the word entered by the user Returns 1 if a new word read, Returns 0 if EOF */ unsigned char GetWord(FILE *wordFile, char *word) { fscanf(wordFile, "%s", word); while ( strlen(word) > MAX_WORD-1 ) fscanf(wordFile, "%s", word); if (feof(wordFile)) return 0; else return 1; }
reading from a text file
Page 1 of 11 Replies - 2176 Views - Last Post: 17 December 2010 - 10:31 PM
#1
reading from a text file
Posted 08 December 2006 - 03:46 PM
Description: reads data from a text file.
Replies To: reading from a text file
#2
Re: reading from a text file
Posted 17 December 2010 - 10:31 PM
the code is to healthy.big up
Page 1 of 1