Input Output Operations on Files

The Standard I/O Library provides similar routines for file I/O to those used  for standard I/O. 

The routine getc(fp) is similar to getchar()  and putc(c,fp) is similar to putchar(c). 

Thus the statement

c = getc(fp); 

reads the next character from the file referenced by fp and the statement
putc(c,fp);
writes the character c into file referenced by fp.
/* file.c: Display contents of a file on screen */ 
#include <stdio.h>
void main() 
{ 
	FILE *fopen(), *fp; 
	int c ; 
	fp = fopen( “prog.c”, “r” ); 
	c = getc( fp ) ; 		
	while (  c != EOF ) 
	{
		putchar( c ); 		
		c = getc ( fp ); 	 
	}
	fclose( fp ); 
}
 In this program, we open the file prog.c for reading. 
We then read a character from the file. This file must exist for this program to work. 
If the file is empty, we are at the end, so getc returns EOF a special value to indicate that the end of file has been reached. (Normally -1 is used for EOF)
The while loop simply keeps reading characters from the file and displaying them, until the end of the file is reached.
The function fclose is used to close the file i.e. indicate that we are finished processing this file. 
We could reuse the file pointer fp by opening another file. 
This program is in effect a special purpose cat command. It displays file contents on the screen, but only for a file called prog.c.
By allowing the user enter a file name, which would be stored in a string, we can modify the above to make it an interactive cat command:
/* cat2.c: Prompt user for filename and display file on screen */
#include <stdio.h>
void main() 
{ 
	FILE *fopen(), *fp; 
	int c ; 
	char filename[40] ;
	printf(“Enter file to be displayed: “);
	gets( filename ) ;
	fp = fopen( filename, “r”);  
 
	c = getc( fp ) ; 		 
	while (  c != EOF ) 
	{
		putchar(c); 		
		c = getc ( fp ); 	
	}
	fclose( fp ); 
}
Latest Current Affairs 2024 Online Exam Quiz for One day Exam Online Typing Test CCC Online Test 2024 Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Sarkari Exam Quiz