Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <stdio.h>
- int count_chars(char block[]) {
- // For with early return is faster than while for this case
- for (int unsigned i = 0; i < 45; i++) {
- if (block[i] == '\0') return --i;
- }
- return i;
- }
- int main() {
- const unsigned int INT_SIZE = sizeof(int unsigned);
- // Defining file pointer
- FILE *fp = fopen("C:\\forlab.txt", "r");
- if (!fp) { // Checking if file exists
- printf("File unavailable.\n", );
- return -1;
- }
- // Defining initial int array
- int unsigned *word_legths = (int unsigned *) malloc(INT_SIZE);
- // Defining initial longest word's length
- int unsigned longest_length = 1;
- // Defining int variable so as not to recreate it in cycle every time
- int unsigned current_size;
- // Ironic, word cannot be longer that this since it is a length of block to read.
- // May be worth to just define original array as unsigned int array of size 255
- char block[45];
- while (!feof(fp)) {
- if (!fscanf(fp, "%45s", block)) {
- // Check if only whitespace remains before EOF and explicitly break cycle
- break;
- }
- // Reading current word's size
- current_size = count_chars(block);
- // Reallocating array, if necessary
- if (current_size > longest_length) {
- word_legths = realloc(word_legths, current_size * INT_SIZE);
- longest_length = current_size;
- }
- // Increasing word count
- word_legths[--current_size]++;
- }
- fclose(fp);
- for (unsigned int i = 0; i < longest_length; i++) {
- if (word_legths[i]) { // Can use implicit compare since everything is unsigned
- printf("Found %d words containing %d letters in supplied file.\n", word_legths[i], i + 1);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment