I just found this thread with the same question but in C#.
How do you achieve this in C
? Is there a better solution than using a loop until it reaches EOF
like this or is there already a function in the libs which can do this?
#include <stdio.h>
#include <stdlib.h>
// ----- Macros -----
#define PATHSIZE 255
#define BUFFERPATHSIZE PATHSIZE + 1
// ----- Functions -----
short get_amount_of_lines_of_file(char * path);
// -----======##### CODDE #####=====-----
int main() {
char buffer[PATHSIZE];
fgets(buffer, BUFFERPATHSIZE, stdin);
printf("%d\n", get_amount_of_lines_of_file(buffer));
return EXIT_SUCCESS;
}
short get_amount_of_lines_of_file(char * path) {
/*
* This will return the amount of lines of a file.
* ----- Variables -----
* lines: The counter of the lines
*
* ----- Return -----
* -1: Couldn't open file
* lines: The amount of lines
*/
FILE *file;
int rofl;
short lines = 0;
if ((file = fopen(path, "r")) != NULL) {
while ((rofl = getc(file)) != EOF)
lines++;
return lines;
}
return EXIT_FAILURE;
}