01
Write a C program that counts lines, words and characters in a file.
Show answer
Read character by character with fgetc.
FILE *fp = fopen(path, "r");
if (!fp) { perror("fopen"); return 1; }
long lines = 0, words = 0, chars = 0;
int c, inWord = 0;
while ((c = fgetc(fp)) != EOF) {
chars++;
if (c == '\n') lines++;
if (isspace(c)) inWord = 0;
else if (!inWord) { inWord = 1; words++; }
}
fclose(fp);
printf("%ld %ld %ld\n", lines, words, chars);
c is int so EOF can be distinguished from valid bytes.