imcrazytwkr

Counting words in file with dynamic memory reallocation in C

Sep 22nd, 2017
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.71 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3.  
  4. int count_chars(char block[]) {
  5.   // For with early return is faster than while for this case
  6.   for (int unsigned i = 0; i < 45; i++) {
  7.     if (block[i] == '\0') return --i;
  8.   }
  9.  
  10.   return i;
  11. }
  12.  
  13. int main() {
  14.   const unsigned int INT_SIZE = sizeof(int unsigned);
  15.  
  16.   // Defining file pointer
  17.   FILE *fp = fopen("C:\\forlab.txt", "r");
  18.  
  19.   if (!fp) { // Checking if file exists
  20.     printf("File unavailable.\n", );
  21.     return -1;
  22.   }
  23.  
  24.   // Defining initial int array
  25.   int unsigned *word_legths = (int unsigned *) malloc(INT_SIZE);
  26.  
  27.   // Defining initial longest word's length
  28.   int unsigned longest_length = 1;
  29.  
  30.   // Defining int variable so as not to recreate it in cycle every time
  31.   int unsigned current_size;
  32.  
  33.   // Ironic, word cannot be longer that this since it is a length of block to read.
  34.   // May be worth to just define original array as unsigned int array of size 255
  35.   char block[45];
  36.  
  37.   while (!feof(fp)) {
  38.     if (!fscanf(fp, "%45s", block)) {
  39.       // Check if only whitespace remains before EOF and explicitly break cycle
  40.       break;
  41.     }
  42.  
  43.     // Reading current word's size
  44.     current_size = count_chars(block);
  45.  
  46.     // Reallocating array, if necessary
  47.     if (current_size > longest_length) {
  48.       word_legths = realloc(word_legths, current_size * INT_SIZE);
  49.       longest_length = current_size;
  50.     }
  51.  
  52.     // Increasing word count
  53.     word_legths[--current_size]++;
  54.   }
  55.  
  56.   fclose(fp);
  57.  
  58.   for (unsigned int i = 0; i < longest_length; i++) {
  59.     if (word_legths[i]) { // Can use implicit compare since everything is unsigned
  60.       printf("Found %d words containing %d letters in supplied file.\n", word_legths[i], i + 1);
  61.     }
  62.   }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment