C Program to display the contents of a file

In a C Program, the contents of a file are read using the function pointer in getc() function. The contents which are read are printed on the output screen using putchar() function.
In this way this program reads and prints the contents of a file.




Souce code:

#include<stdio.h>
#include<string.h>
int main()
{
FILE *fp;
int ch;
char fname[30];
printf("\n Enter the filename : ");
fflush(stdin);
scanf("%s",fname); //Step 1
fp = fopen(fname, "r"); //Step 2
while(fp ==NULL) //Step 3
{
printf("Cannot open the file %s for reading \n", fname);
printf("\n Enter the filename: ");
fflush(stdin);
scanf("%[^\n]",fname);
fp = fopen(fname, "r");
}
ch = getc(fp);
while(ch != EOF) //Step 4
{
putchar(ch);
ch = getc(fp);
}
fclose(fp); //Step 5
return 0;
}

Sample test cases:

1.  Enter the filename : 1.txt
    Hello
    This is topoint
    It is a repository of c programs

2. Enter the filename : Doesnotexist
   Cannot open the file : Doesnotexist for reading
   Enter the filename:1.txt
   Hii
   This is topoint
   It is a repository of c programs

Explanation:

Step 1: The file name is read from the user using scanf() function.
Step 2: The file is opened using the fopen() function in reading mode.
Step 3: If file does not exist then file pointer content will be NULL. In that case another file is read from the user using scanf() function.
Step 4: This while loop places the every character of the input file on to the output screen using putchar() function.
Step 5: Finally the file is closed using fclose() function.