ADVERTISEMENT
ADVERTISEMENT

freopen() function in C language with Example

Here, we are going to learn about the freopen() function of library header stdio.h in C language with its syntax, example.
Submitted by Souvik Saha, on January 11, 2019

freopen() function in C

Prototype:

    FILE* freopen(const char *str, const char *mode, FILE *stream);

Parameters:

    const char *str, const char *mode, FILE *stream

Return type: FILE*

Use of function:

The prototype of the function freopen() is:

    FILE* freopen(const char *str, const char *mode, FILE *stream);

The freopen() function opens the existing stream into another file. The end-of-file and error flag is cleared in this process. The file named as str with its operation mode, opens it into the file stream named as stream. The freopen() function acts similar to the fopen() function. In the following output we can see the work of the function.

freopen() example in C

#include <stdio.h>
#include <stdlib.h>

int main()
{
    //Initialize the file pointer
    FILE *f, *fp;
    //Take a array of characters
    char ch[100];

    //Create the file for write operation
    f = fopen("includehelp.txt", "w");

    printf("Enter five strings\n");
    for (int i = 0; i < 4; i++) {
        //take the strings from the users
        scanf("%[^\n]", &ch);
        //write back to the file
        fputs(ch, f);
        //every time take a new line for the new entry string
        //except for last entry.Otherwise print the last line twice
        fputs("\n", f);

        //clear the stdin stream buffer
        //if we don't write this then after taking string
        fflush(stdin);
    }

    //%[^\n] is waiting for the '\n' or white space
    //take the strings from the users
    scanf("%[^\n]", &ch);
    fputs(ch, f);

    //reopen the file for read operation
    fp = freopen("includehelp.txt", "r", fp);

    printf("File content is--\n");
    printf("\n...............print the strings..............\n\n");
    while (!feof(fp)) {
        //takes the first 100 character in the character array
        fgets(ch, 100, fp);
        //and print the strings
        printf("%s", ch);
    }
 
    //close the files
    fclose(fp);
    fclose(f);

    return 0;
}

Output

freopen example in c

C stdio.h Library Functions Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.