C Library Function - freopen()
Description
C Library Function **FILE *freopen(const char *filename, const char mode, FILE stream) Associate a new filename filename with the given open stream stream , while closing 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)
Parameters
- filename -- This is a C string containing the name of the file to be opened.
- mode -- This is a C string containing the file access mode, which is as follows:
| Mode | Description |
|---|---|
| "r" | Open a file for reading. The file must exist. |
| "w" | Create an empty file for writing. If a file with the same name already exists, its contents are deleted and the file is treated as a new empty file. |
| "a" | Append to a file. Write operations append data to the end of the file. If the file does not exist, it is created. |
| "r+" | Open a file for updating, both reading and writing. The file must exist. |
| "w+" | Create an empty file for reading and writing. |
| "a+" | Open 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 identifying the stream. Otherwise, it returns a null pointer.
Example
The following example demonstrates the use of the freopen() function.
#include
int main ()
{
FILE *fp;
printf("该文本重定向到 stdout\n");
fp = freopen("file.txt", "w+", stdout);
printf("该文本重定向到 file.txt\n");
fclose(fp);
return(0);
}
Let's compile and run the above program; this will send the following lines to standard output STDOUT, because initially we did not open standard output:
该文本重定向到 stdout
When calling freopen() After that, it associates standard output STDOUT with the file file.txt, so whatever we write to standard output STDOUT will be written to file.txt, and the file file.txt will have the following contents.
该文本重定向到 file.txt
Now let us use the following program to view the content of the file above:
#include
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);
}
C Standard Library -