C Program to count number of characters in the file


Levels of difficulty: / perform operation:

Program to count number of characters in the file. In this program you can learn c file operations. Here we counting the characters by reading the characters in the file one by one and if read character was not an ‘\n’ ,’\t’ or EOF, it increments the counter by one.

C Program

#include<stdio.h>
#include<conio.h>
void main() {
	char ch;
	int count=0;
	FILE *fptr;
	clrscr();
	fptr=fopen("text.txt","w");
	if(fptr==NULL) {
		printf("File can't be created\a");
		getch();
		exit(0);
	}
	printf("Enter some text and press enter key:\n");
	while((ch=getche())!='\r') {
		fputc(ch,fptr);
	}
	fclose(fptr);
	fptr=fopen("text.txt","r");
	printf("\nContents of the File is:");
	while((ch=fgetc(fptr))!=EOF) {
		count++;
		printf("%c",ch);
	}
	fclose(fptr);
	printf("\nThe number of characters present in file is: %d",count);
	getch();
}





Quantitative Aptitude
Reasoning
Programming
Interview