Saturday 18 December 2010

Program To display the contents of a file

Description:

The program will read the contents of a given file and displays on the screen

Program:

#include <stdio.h>
#include <stdlib.h>

int main()
{
   char ch, file_name[25];
   FILE *fp;

   printf("Enter the name of file you wish to see\n");
   gets(file_name);

   fp = fopen(file_name,"r"); // read mode

   if( fp == NULL )
   {
      perror("Error while opening the file.\n");
      exit(EXIT_FAILURE);
   }

   printf("The contents of %s file are :\n", file_name);

   while( ( ch = fgetc(fp) ) != EOF )
      printf("%c",ch);

   fclose(fp);
   return 0;
}

Output:

Enter the name of the file you want to see
Red

The contents of file red are:
Hello this a simple file create to test the file funmnctions of c
Fopen is used to open the file .fclose is used to close file.

Enter the name of the file you want to see
Bill

The file doesn’t exist

Conclusion:  The program is error free



Algorithm


No comments:

Post a Comment