Guest User

Untitled

a guest
Jan 18th, 2019
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.70 KB | None | 0 0
  1. /**
  2.  * Counts the amount of lines (\n) in given file
  3.  * @param f The file to be used
  4.  * @return The number of lines in the file
  5.  */
  6. int getNumberOfLines(FILE *f) {
  7.     int count = 0;
  8.  
  9.     //start from the beginning
  10.     fseek(f, 0, SEEK_SET);
  11.  
  12.     //read
  13.     char * buf = new char[BUFFERING_BLOCK_SIZE];
  14.     for (;;) {
  15.         //read a nice chunk (to minimize head seek overhead)
  16.         size_t amount_read = fread(buf, sizeof(char), BUFFERING_BLOCK_SIZE, f);
  17.         if (amount_read == 0)
  18.             break;
  19.         //count occurrences of '\n' in that chunk
  20.         for (size_t i = 0; i < amount_read; i++) {
  21.             if (buf[i] == '\n')
  22.                 count++;
  23.         }
  24.     }
  25.     free(buf);
  26. //  if (DEBUG)
  27. //      cout << "Number of lines:\t" << count << endl;
  28.     return count;
  29. }
Add Comment
Please, Sign In to add comment