The C library FILE *freopen(const char *filename, const char *mode, FILE *stream) function associates a new filename with the given open stream and at the same time closes the old file in the stream.
SyntaxFollowing is the C library syntax of the freopen() function −
FILE *freopen(const char *filename, const char *mode, FILE *stream);Parameters
Below is the list of parameter that can be used within the parenthesis of C library function freopen() −
On success, freopen returns a pointer to the FILE object. On failure, it returns NULL and sets the global variable errno to indicate the error.
Example 1: Redirecting Standard Output to a FileThis example redirects the standard output (stdout) to a file named output.txt.
Below is the illustration of C library freopen() function −
#include <stdio.h> int main() { FILE *fp = freopen("output.txt", "w", stdout); if (fp == NULL) { perror("freopen"); return 1; } printf("This will be written to the file output.txt instead of standard output.\n"); fclose(fp); return 0; }Output
The above code produces following result in output.txt file −
This will be written to the file output.txt instead of standard output.Example 2: Redirecting Standard Input to a File
This example redirects the standard input (stdin) to read from a file named input.txt and prints its contents to standard output.
#include <stdio.h> int main() { FILE *fp = freopen("input.txt", "r", stdin); if (fp == NULL) { perror("freopen"); return 1; } char buffer[100]; while (fgets(buffer, sizeof(buffer), stdin) != NULL) { printf("%s", buffer); } fclose(fp); return 0; }Output
After execution of above code, we get the following result o terminal and the content of input.txt remains unchanged:
Line 1: This is the first line. Line 2: This is the second line.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4