Open a file and display it - C File

C examples for File:File Read

Description

Open a file and display it

Demo Code

#include <stdio.h>
#include <stdlib.h>  // for exit()
int main()//from  w w  w . j  a va2 s . c o  m
{
    int ch;
    FILE * fp;
    char fname[50];         
    
    printf("Enter the name of the file: ");
    scanf("%s", fname);
    fp = fopen(fname, "r"); // open file for reading
    if (fp == NULL)         // attempt failed
    {
      printf("Failed to open file. Bye\n");
      exit(1);            // quit program
    }
    // getc(fp) gets a character from the open file
    while ((ch = getc(fp)) != EOF)
        putchar(ch);
    fclose(fp);             
    
    return 0;
}

Result


Related Tutorials