| << Prev | Beej's Guide to C | Next >> |
Reopen an existing
#include <stdio.h> FILE *freopen(const char *filename, const char *mode, FILE *stream);
Let's say you have an existing
Why on Earth would you ever want to do that? Well, the most common reason would be if you had a program that normally would read from stdin, but instead you wanted it to read from a file. Instead of changing all your scanf()s to fscanf()s, you could simply reopen stdin on the file you wanted to read from.
Another usage that is allowed on some systems is that you can pass
When you call freopen(), the old stream is closed. Otherwise, the function behaves just like the standard fopen().
freopen() returns stream if all goes well.
If something goes wrong (e.g. you tried to open a file for read that
didn't exist), fopen() will return
#include <stdio.h>
int main(void)
{
int i, i2;
scanf("%d", &i); // read i from stdin
// now change stdin to refer to a file instead of the keyboard
freopen("someints.txt", "r", stdin);
scanf("%d", &i2); // now this reads from the file "someints.txt"
printf("Hello, world!\n"); // print to the screen
// change stdout to go to a file instead of the terminal:
freopen("output.txt", "w", stdout);
printf("This goes to the file \"output.txt\"\n");
// this is allowed on some systems--you can change the mode of a file:
freopen(NULL, "wb", stdout); // change to "wb" instead of "w"
return 0;
}
| << Prev | Beej's Guide to C | Next >> |