Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- struct wordNode* generate(char*);
- void searchAndPlace(char*, struct wordNode*);
- void outputToFile(char*, struct wordNode*);
- int main(int argc, char* argv[])
- {
- struct wordNode
- {
- char* word;
- int count;
- struct wordNode* next;
- }
- outputToFile(argv[2], generate(argv[1]);
- return 0;
- }
- struct wordNode* generate(char* inputFile[])
- {
- char oneWord[100];
- char c;
- char* storedWord[];
- struct wordNode* head;
- int first = 1; //use as boolean, true if function is processing the first word of a text
- FILE *file = fopen(inputFile, "r");
- if(file == NULL)
- {
- printf("Could not open %s \n", inputFile);
- return NULL;
- }
- else
- {
- do
- {
- c = fscanf(file, "%s", oneWord); //grabs one word, stores in oneWord, c = next char after
- if(first == 1)
- {
- storedWord = malloc(size_of(oneWord)); //allocate space in heap for word
- strcpy(storedWord, oneWord); //copy word into allocated space
- struct wordNode w1 = {storedWord, 1, NULL};
- head = malloc(size_of(w1)); //need to copy struct to this malloc location somehow
- }
- else
- {
- searchAndPlace(oneWord, head);
- }
- }while(c != EOF);
- fclose(file);
- return head;
- }
- }
- void searchAndPlace(char* key[], struct wordNode* head)
- {
- int found = 0; //use as boolean, false unless node containing key word is found
- int i = 0;
- while(key[i])
- {
- key[i] = putchar(tolower(key[i]));
- i++;
- }
- while(head != NULL && found == 0)
- {
- if(strcmp(head -> word, key) == 0) //current node contains the key word
- {
- head -> count++;
- found = 1;
- }
- else if(strcmp(head -> next -> word, key) > 0) //the next word is too far alphabetically, i.e. if the word wasn't "new" we would have found it by now
- {
- struct wordNode* w = {malloc(size_of(key)), 1, head -> next};
- head -> next = w;
- }
- else if(head -> next == NULL) //we've reched the end of the list
- {
- struct wordNode* w = {malloc(size_of(key)),1,NULL};
- }
- }
- }
- void outputToFile(struct wordNode* head, char* outputFile[])
- {
- FILE *file;
- file = fopen(outputFile, "w");
- while(head != NULL)
- {
- int fputs(file, "%s %d \n", head -> word, head -> count);
- head = head -> next;
- }
- fclose(file);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement