C language file input/output ACM Improved (Freopen function)May 27, 2009 10:379,457 views post Comments Read comments
Article Jiangnan (Slyar) Article Source: Slyar Home (www.slyar.com) reprinted please specify, thank you for your cooperation.
Yesterday sent a "C language use file input/output data", using the most common file input/output method, Felix Daniel then gave a more simple method of improvement, in the ACM application is very wide, and great, and now to introduce.
The file opening function used this time is no longer fopen, but another function contained in stdio.h Freopen
FILE * Freopen (const char * filename, const char * mode, FILE * stream);
"Parameter description"
FileName: The file name to open
Mode: The file opens with the same mode as in fopen (R/W)
Stream: A file pointer, typically using a standard stream file (Stdin/stdout/stderr)
"How to use"
Because the file pointer uses a standard stream file, we can not define a file pointer.
Next we use the Freopen () function to open the input file as read-only R (read) slyar.in
Freopen ("Slyar.in", "R", stdin);
Then use the Freopen () function to open the output file in write mode W (write) Slyar.out
Freopen ("Slyar.out", "w", stdout);
The next thing is the advantage of using the freopen () function, we no longer need to modify scanf and printf, but to maintain the code as it is. Because the Freopen () function redirects the standard stream to the file specified earlier, save time and effort, like ...
Finally, just use fclose to close the input file and output file.
Fclose (stdin);
Fclose (stdout);
To recover a handle, you can reopen the standard console device file, except that the name of the device file is associated with the operating system.
Dos/win:
Freopen ("CON", "R", stdin);
Linux:
Freopen ("/dev/console", "R", stdin);
Also attach a code template:
12345678910111213 |
#include <stdio.h> int main () {freopen ("slyar.in", "R", stdin), Freopen ("Slyar.out", "w", stdout);/* Write the code as-is in the middle, Nothing to modify * * * fclose (stdin); fclose (stdout); return 0;} |
PS. Just found a problem, is in the use of C-free compiled with the file operation of the source code, you have to put fopen or freopen to all variable definitions below, otherwise it will compile the error ... 囧
Go C language file input/output ACM Improved (Freopen function)