Read and display data from file on screen - C

Write a C program to read data from a text file and display the data on the screen. If file does not exist, create a file.

Solution:

#include <stdio.h>
#include <stdlib.h> // For exit()
int main()
{
      FILE *fp;
      char fname1[50],ch;
      printf("Enter filename to open for reading : ");
      scanf("%s", fname1);
      // Open one file for reading
      fp = fopen(fname1, "r");
      if (fp == NULL)
      {
            fp = fopen(fname1, "w");
            printf("\n%s file does not exist hence file created..", fname1);
            //exit(0);
      }
      while((ch=fgetc(fp))!=EOF)
      {
            printf("%c", ch);
      }
      fclose(fp);
      return 0;
}


Output:

display data

In above output, we enter file name source.txt. If this file is present at same location where your program is saved then it will display the content in that file.

display data

In above output, we enter file name num.txt. This file is not present hence it creates a file at same location where your program is saved.