This C program takes a filename as a command-line parameter and reads the specified text file line by line. It counts the number of characters and words in each line and prints the results. Additionally, it displays the total number of lines in the text file.
The file name should include either the complete physical path or just the file name if the file is in the same directory as the program executable. The program has been updated for better readability, correctness, and improved handling of spaces and tabs.
Enhance your knowledge of C programming with these valuable resources:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
FILE *fp;
int nchars, nwords, nlines;
int lastnblank; /* 0 iff the last character was a space or tab */ char c;
if (argc != 2) {
printf("Usage: %s filename\n", argv[0]);
exit(EXIT_FAILURE);
}
if ((fp = fopen(argv[1], "r")) == NULL) {
perror("fopen");
exit(EXIT_FAILURE);
}
nchars = nwords = nlines = lastnblank = 0;
while ((c = getc(fp)) != EOF) {
nchars++;
if (c == '\n') {
if (lastnblank)
nwords++;
printf("words=%d, characters=%d\n", nwords, nchars);
nchars = nwords = lastnblank = 0;
nlines++;
} else {
if ((c == ' ' || c == '\t') && lastnblank)
nwords++;
lastnblank = (c != ' ' && c != '\t');
}
}
// Handle the case when the last line doesn't end with a newline character
if (lastnblank)
nwords++;
printf("words=%d, characters=%d\n", nwords, nchars);
printf("lines=%d\n", nlines + (nlines > 0 || nchars > 0 ? 1 : 0));
fclose(fp);
return 0;
}