Advertisement
Acninetyfive

wordc.c new

Feb 11th, 2016
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.11 KB | None | 0 0
  1. #include<stdio.h>
  2.  
  3. struct wordNode* generate(char*);
  4. void searchAndPlace(char*, struct wordNode*);
  5. void outputToFile(char*, struct wordNode*);
  6.  
  7. int main(int argc, char* argv[])
  8. {
  9. struct wordNode
  10. {
  11. char* word;
  12. int count;
  13. struct wordNode* next;
  14. }
  15.  
  16. outputToFile(argv[2], generate(argv[1]);
  17.  
  18. return 0;
  19. }
  20.  
  21.  
  22.  
  23. struct wordNode* generate(char* inputFile[])
  24. {
  25. char oneWord[100];
  26. char c;
  27. char* storedWord[];
  28. struct wordNode* head;
  29. int first = 1; //use as boolean, true if function is processing the first word of a text
  30.  
  31. FILE *file = fopen(inputFile, "r");
  32. if(file == NULL)
  33. {
  34. printf("Could not open %s \n", inputFile);
  35. return NULL;
  36. }
  37. else
  38. {
  39. do
  40. {
  41. c = fscanf(file, "%s", oneWord); //grabs one word, stores in oneWord, c = next char after
  42. if(first == 1)
  43. {
  44. storedWord = malloc(size_of(oneWord)); //allocate space in heap for word
  45. strcpy(storedWord, oneWord); //copy word into allocated space
  46. struct wordNode w1 = {storedWord, 1, NULL};
  47. head = malloc(size_of(w1)); //need to copy struct to this malloc location somehow
  48. }
  49. else
  50. {
  51. searchAndPlace(oneWord, head);
  52. }
  53. }while(c != EOF);
  54.  
  55. fclose(file);
  56. return head;
  57. }
  58. }
  59.  
  60. void searchAndPlace(char* key[], struct wordNode* head)
  61. {
  62. int found = 0; //use as boolean, false unless node containing key word is found
  63. int i = 0;
  64.  
  65.  
  66. while(key[i])
  67. {
  68. key[i] = putchar(tolower(key[i]));
  69. i++;
  70. }
  71.  
  72. while(head != NULL && found == 0)
  73. {
  74. if(strcmp(head -> word, key) == 0) //current node contains the key word
  75. {
  76. head -> count++;
  77. found = 1;
  78. }
  79. 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
  80. {
  81. struct wordNode* w = {malloc(size_of(key)), 1, head -> next};
  82. head -> next = w;
  83. }
  84.  
  85. else if(head -> next == NULL) //we've reched the end of the list
  86. {
  87. struct wordNode* w = {malloc(size_of(key)),1,NULL};
  88. }
  89. }
  90. }
  91.  
  92. void outputToFile(struct wordNode* head, char* outputFile[])
  93. {
  94.  
  95.  
  96. FILE *file;
  97. file = fopen(outputFile, "w");
  98.  
  99. while(head != NULL)
  100. {
  101. int fputs(file, "%s %d \n", head -> word, head -> count);
  102. head = head -> next;
  103. }
  104.  
  105. fclose(file);
  106. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement