C Library Functions -freopen()
C Standard Library - <stdio.h>
Description
C Library FunctionsFILE *freopen(const char *filename, const char *mode, FILE *stream)Associates a new file namefilenamewith the given open stream,streamand closes the old file in the stream.
Declaration
Below is the declaration of the freopen() function.
FILE *freopen(const char *filename, const char *mode, FILE *stream)
Parameter
- filename-- This is the C string containing the name of the file to be opened.
- mode-- This is the C string containing the file access mode, with the modes as follows:
| Mode | Description |
|---|---|
| "r" | Opens a file for reading. The file must exist. |
| "w" | Creates an empty file for writing. If the file name is the same as an existing file, the existing file's content is deleted, and the file is treated as a new empty file. |
| "a" | Appends to a file. Write operations append data to the end of the file. If the file does not exist, it is created. |
| "r+" | Opens a file for updating, which can be read and written. The file must exist. |
| "w+" | Creates an empty file for reading and writing. |
| "a+" | Opens a file for reading and appending. |
- stream-- This is a pointer to a FILE object that identifies the stream to be reopened.
Return Value
If the file is opened successfully, the function returns a pointer to the object that identifies the stream. Otherwise, it returns a null pointer.
Example
The following example demonstrates the usage of the freopen() function.
#include <stdio.h>
int main ()
{
FILE *fp;
printf("该文本重定向到 stdout\n");
fp = freopen("file.txt", "w+", stdout);
printf("该文本重定向到 file.txt\n");
fclose(fp);
return(0);
}
Let us compile and run the above program, which will send the following lines to the standard output STDOUT, because initially we did not open the standard output:
该文本重定向到 stdout
When callingfreopen()After that, it associates the standard output STDOUT with the file,file.txtand no matter what we write to the standard output STDOUT, it will be written to file.txt, so the file file.txt will have the following content.
该文本重定向到 file.txt
Now let's use the following program to view the content of the above file:
#include <stdio.h>
int main ()
{
FILE *fp;
int c;
fp = fopen("file.txt","r");
while(1)
{
c = fgetc(fp);
if( feof(fp) )
{
break ;
}
printf("%c", c);
}
fclose(fp);
return(0);
}
other extensions