This function may be used for opening a file in different modes. The function prototype may be written in the following manner:
FILE *freopen(const char* filename, const char* mode, FILE* stream);
The function opens the file whose name is the string filename in a mode pointed to by mode and associates it with the stream pointed to by stream. The function returns pointer to stream if successful otherwise it returns a NULL pointer. Program provides an illustration for re-opening a file in different modes.
#include <stdio.h> #include <stdlib.h> void main() { FILE* fptr; //filestream fptr = fopen ("Student_file","w"); clrscr(); if( fptr ==NULL) //test if fopen () fails to open file. { printf("File could not be opened."); exit (1); } else printf("File Student_fileis open for writing.\n"); freopen ("Student_file","a", fptr); /* reopen filefor appending*/ if(fptr ==NULL) printf( "Failed to reopen"); else printf ("Student_file is opened in append mode.\n"); freopen ("Student_file","r", fptr); /* reopen filefor appending*/ if(fptr ==NULL) printf( "Failed to reopen"); else printf("The file is open for reading.\n"); fclose(fptr); }