C program to read a text file character by character

C program to read a text file character by character and display content on the console screen. This program will read special characters also and is independent of the file size.

The fgetc or getc function can be used to read characters. However, this c source code example will use fgetc.

[ The difference between getc and fgetc is that getc can be implemented as a macro, whereas fgetc cannot be implemented as a macro. fgetc is guaranteed to be a function with no side effects. ]

Here is the snips of the code that read characters till end of file and display content on the screen. fip is input file pointer.


while((c=fgetc(fip))!=EOF){
/*display content of file on console char by char*/
putchar(c);
}

C Source code example to read a text file char by char

/*--- C program to read a text file character by character ---*/
#include<stdio.h>
int main(){


	/*variable c will be used for comparision with EOF
	* c is int type not char type, since EOF is a negative number,
	* and a plain char may be unsigned.
	* int type of c will also guarantee that EOF is not equal
	* to any valid character
	*/
	int c;

	FILE *fip = NULL;// file handle initialize with NULL

	/*Open the text file in read mode so we
	* cannot modify the file accidently in the 
	* program
	*/

	//put the text file in current directory where
	//you have project file or you have to give full 
	//path e.g. fip = fopen("D:\\test\\in.txt","r+");	
	fip = fopen("in.txt","r+");
	

	if(fip == NULL){
		/*If file opening fails return from here itself*/
		printf("Error, Can't open file\n");
		return 0;
	}

	/*File is opened. Start reading the file character by character*/	

	while((c=fgetc(fip))!=EOF){
		/*display content of file on console char by char*/
		putchar(c);
	}
	/*close the file*/
	fclose ( fip );

	return 0;
}

NOTE:

Variable c will be used for comparison with EOF.  c is int type not char type, since EOF is a negative number, and a plain char may be unsigned. int type of c will also guarantee that EOF is not equal to any valid character.

Related Posts