Friday, April 11, 2014

C Program to open an existing file and read it

C Program to open an existing file and read it

You have to save the file which you want to read in the home folder (ie in the folder where your c program exists with ). Give the name of file with its extension (like name.txt) when it is asked.

#include <stdlib.h>
#include<stdio.h>
int main()
{
    FILE *fptr;
    char filename[15];
    char ch;
//    clrscr();

    printf("Enter the filename to be opened \n");
    scanf("%s", filename);
    /*  open the file for reading */
    fptr = fopen(filename, "r");
    if (fptr == NULL)
    {
printf("Cannot open file \n");
exit(0);
    }
    ch = fgetc(fptr);
    while (ch != EOF)
    {
printf ("%c", ch);
ch = fgetc(fptr);
    }
    fclose(fptr);
}

No comments:

Post a Comment