banovski

Identifying records in a file and reading them

Feb 27th, 2022 (edited)
607
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.98 KB | None | 0 0
  1. /* The task: write a program, showfroot.c, that displays each record
  2.  * in the froot.txt file. Use fread() to read in each file chunk. Have
  3.  * each chunk displayed along with its record number using this
  4.  * format: "14: Melon". */
  5.  
  6. #include <stdio.h>
  7.  
  8. int main()
  9. {
  10.      int i = 0;
  11.      int prev;
  12.      int curr = 0;
  13.      int record_number = 0;
  14.      int char_counter = 0;
  15.      int record_length;
  16.  
  17.      /* Reading the file */
  18.      FILE *the_file;
  19.      the_file = fopen("froot.txt", "r");
  20.      if(!the_file)
  21.      {
  22.           puts("Error reading file");
  23.           return(1);
  24.      }
  25.  
  26.      /* Figuring out the number of records by counting
  27.       * "non-null -- null" combinations, printing
  28.       * statistics */
  29.      while(curr != EOF)
  30.      {
  31.           prev = curr;
  32.           curr = fgetc(the_file);
  33.           if(prev != 0 && curr == 0)
  34.                record_number++;
  35.           char_counter++;
  36.      }
  37.      record_length = char_counter / record_number;
  38.      printf("There are %d records in the file, %d characters each: \n", record_number, record_length);
  39.      rewind(the_file);
  40.  
  41.      char froot[record_number][record_length];
  42.  
  43.      /* reading the records */
  44.      fread(froot, record_length, record_number, the_file);
  45.  
  46.      /* printing the records */
  47.      for(i = 0; i < record_number; i++)
  48.      {
  49.           if(i > 0 && i % 5 == 0)
  50.                putchar('\n');
  51.           printf("%2d: %-*s", i + 1, record_length, froot[i]);
  52.      }
  53.      putchar('\n');
  54.      return(0);
  55. }
  56.  
  57. /* There are 25 records in the file, 14 characters each:
  58.  *  1: Apple          2: Avocado        3: Banana         4: Blackberry     5: Boysenberry
  59.  *  6: Cantaloupe     7: Cherry         8: Coconut        9: Cranberry     10: Cumquat
  60.  * 11: Grape         12: Guava         13: Mango         14: Marionberry   15: Melon
  61.  * 16: Orange        17: Papaya        18: Peach         19: Pear          20: Persimmon
  62.  * 21: Pineapple     22: Plum          23: Raspberry     24: Strawberry    25: Watermelon */
  63.  
Add Comment
Please, Sign In to add comment