Balo Balo - 1 month ago 9
C Question

C program which counts chars and newlines in txt file

My program counts the number of chars and newlines, somehow the chars count isn't correct. TEST.TXT contains 58 chars, but the program counts 53. What am I doing wrong? The amount of new lines is 5 and that is correct.

#include <stdio.h>
#include <stdlib.h>

int main() {
FILE *fPointer;
fPointer = fopen("TEST.TXT", "r");

int newline_count = 0;
int c;
int charcount = 0;

while ((c = fgetc(fPointer)) != EOF) {
if (c == '\n')
newline_count++;
if (c != '\n')
charcount++;
}

printf("chars = %d ", charcount);
printf("newlines = %d\n", newline_count);

return 0;
}


This is the input file

Answer

The input text file contains 53 characters excluding the 5 newline characters. If you want the new line characters to be counted into the overall character calculation you should change the while loop content as follows:

while ((c = fgetc(fPointer)) != EOF) {
    /* Increment total character count until EOF is reached */
    charcount++;

    /* Increment newline character count if '\n' is found */
    if (c == '\n')
        newline_count++;  
}