File Operations

There are different operations that can be carried out on a file. These are:
(a)Creation of a new file
(b)Opening an existing file
(c)Reading from a file
(d)Writing to a file
(e)Moving to a specific location in a file (seeking)
(f)Closing a file
Let us now write a program to read a file and display its contents on the screen. We will first list the program and show what it does, and then dissect it line by line. Here is the listing….

#include <stdio.h>
#include <stdlib.h>
int main( )
	FILE *fp;
	char ch;
	fp = fopen ("file1.txt","r");
	while (1)
		ch = fgetc ( fp );
		if ( ch == EOF )
		printf ("%c",ch);
	fclose ( fp );
    return 0;

On execution of this program it displays the contents of the file ‘file1.txt’ on the screen. Let us now understand how it does the same.


You may also like...