In C file handling, we can read a program file and count the number of capital and small letters present inside it. In this program, the file is opened in "rt" (read text) mode. Each character is read using fgetc() and checked using character comparison conditions.
How It Works?
FILE *fp.cap and small to store the count of capital and small letters.fopen() in read mode.fgetc().'A' to 'Z' and increase the capital letter count.'a' to 'z' and increase the small letter count.#include <stdio.h> #include <conio.h> main() { FILE *fp; int cap = 0, small = 0; char ch; clrscr(); fp = fopen("file1.c", "rt"); while(!feof(fp)) { ch = fgetc(fp); printf("%c", ch); if(ch >= 'A' && ch <= 'Z') { cap++; } if(ch >= 'a' && ch <= 'z') { small++; } } printf("\n capital latters is %d", cap); printf("\n small latters is %d", small); fclose(fp); getch(); }
fopen("data.txt","rt"). Use fgetc() to read each character and check:
'A' to 'Z' → Capital letters'a' to 'z' → Small letters#include <stdio.h> #include <conio.h> main() { FILE *fp; int cap = 0, small = 0; char ch; clrscr(); fp = fopen("data.txt", "rt"); while(!feof(fp)) { ch = fgetc(fp); if(ch >= 'A' && ch <= 'Z') { cap++; } if(ch >= 'a' && ch <= 'z') { small++; } } printf("\n Capital Letters = %d", cap); printf("\n Small Letters = %d", small); fclose(fp); getch(); }
data.txt file in read mode. It reads each character using fgetc() and checks whether the character belongs to the uppercase or lowercase alphabet range. The counters cap and small are increased accordingly, and the final count is displayed.