C Programming Ex10
C Programming Ex10
PROCEDURE:
Step 1: Start
Step 2: Read the file name
Step 3: Open the given file
Step 4: for each character in the file
characters++;
if the character is newline then
lines++;
if character is ' ' || '\n' || '\t' || '\0' then
words++;
Step 5: Display the total number of characters, words, and lines
Step 6: Stop
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
void main()
{
FILE *file;
char filename[100];
char ch;
int characters = 0, words = 0, lines = 0;
clrscr();
printf("Enter the filename: ");
scanf("%s", filename);
file = fopen(filename, "r");
if (file == NULL) {
printf("Could not open file %s\n", filename);
return 1;
}
while ((ch = fgetc(file)) != EOF) {
characters++;
if (ch == '\n' || ch == '\0') {
lines++;
}
if (ch == ' ' || ch == '\n' || ch == '\t' || ch == '\0') {
words++;
}
}
fclose(file);
printf("\n Characters: %d ", characters);
printf("\n Words: %d ", words);
printf("\n Lines: %d ", lines);
getch();
}
RESULTS:
Thus, the C program to count the number of characters, words, and lines
in a file was successfully executed.