/* fileIODemo1.c - uses prototypes - declares arrays - passes arrays to functions - loads array from a TEXT file - uses command line args to specify input file - uses fscanf - TO COMPILE: gcc -o prog fileIODemo1.c - TO EXECUTE: ./prog text-file */ /****** ** Exercise 1: What happens if the file is opened in "w" "w+" "r+" "a" "a+" ** modes? Caution: Backup the dictionary file before trying. ** ** Exercise 2: Can you write the loadDictionary program without passing the ** wordCount? ** ** Exercise 3: NOTE: TIME CONSUMING and addition to lab 2 ** Modify your lab2 calendar such that it inputs an additional event file. ** Each line in this event file is of the format: ** ** ** The calendar will display the date, day and event in output file (say, ** outEvent.txt) ** Each line in the output will be of the format: ** //: : *****/ #include #include #include #define MAX_WORDS 100 #define MAX_WORD_LEN 30 void loadDictionary(char *fileName, char dictionary[][MAX_WORD_LEN], int *wordCount); void printDictionary(char dictionary[][MAX_WORD_LEN], int wordCount); int main(int argc, char *argv[]) { char dictionary[MAX_WORDS][MAX_WORD_LEN]; int wordCount=0; loadDictionary(argv[1], dictionary, &wordCount); /* pass ADDR of wordCount to modify */ printf("\n%d words read from %s\n", wordCount, argv[1]); printDictionary(dictionary, wordCount); /* pass wordCount's value here */ return 0; } void loadDictionary(char *fileName, char dictionary[][MAX_WORD_LEN], int *wordCount) { FILE *inFile; char wordBuffer[MAX_WORD_LEN]; /* fscanf into this buffer - then strcpy to table */ if ((inFile = fopen(fileName, "r")) == NULL) { fprintf(stderr,"ERROR - Cannot open input file %s. Program exiting!\n", fileName); exit(EXIT_FAILURE); } /* the loading loop will terminate if EOF is reached - OR - if the table fills up */ while ((fscanf(inFile, "%s", wordBuffer) > 0) && (*wordCount < MAX_WORDS)) { strcpy(dictionary[*wordCount], wordBuffer); (*wordCount)++; printf("%3d: %s\n", *wordCount, wordBuffer); /* "%3d" right justifies output value 3 places */ } fclose(inFile); } void printDictionary(char dictionary[][MAX_WORD_LEN], int wordCount) { int i; /* declare vars at TOP of block, not interspersed with code */ printf("\n"); for (i = 0; i < wordCount; ++i) printf("%s ", dictionary[i]); printf("\n"); }