OP's code functions well aside from maybe an off-by-one issue and a last line issue.
Standard C library definition
A text stream is an ordered sequence of characters composed into lines, each line consisting of zero or more characters plus a terminating new-line character. Whether the last line requires a terminating new-line character is implementation-defined. C11dr §7.21.2 2
A line ends with a '\n'
and the last line may or may not end with a '\n
'.
If using the idea that the last line of a file does not require a final '\n
, then the goal is to count the number of occurrences that a character is read after a '\n'
.
// Let us use a wide type
// Start at 0 as the file may be empty
unsigned long long line_count = 0;
int previous = '\n';
int ch;
while ((ch = fgetc(in)) != EOF) {
if (previous == '\n') line_count++;
previous = ch;
}
printf("Line count:%llu\n", line_count);
Reading a file one character at a time may be less efficient than other means, but functionally meets OP goal.
This answer uses (ch = fgetc(in)) != EOF
instead of fscanf(in,"%c",&c) == 1
which is typically ""faster", but with an optimizing compiler, either may emit similar performance code. Such details of speed can be supported with analysis or profiling. When in doubt, code for clarity.