The file opening function used this time is no longer fopen, but another function freopen contained in stdio. h.
File*Freopen( Const Char *Filename, Const Char *Mode,File*Stream);
[Parameter description]
Filename: name of the file to be opened
Mode: the mode in which the file is opened, which is the same as the mode in fopen (R/W ).
Stream: file pointer, usually using standard stream files (stdin/stdout/stderr)
[Usage]
Because the file pointer uses a standard stream file, we can not define the file pointer.
Next, use the freopen () function to open the input file slyar. In in read-only mode R (read ).
Freopen("Slyar. In", "R",Stdin);
Then use the freopen () function to open the output file slyar. Out in write mode W (write ).
Freopen("Slyar. Out", "W",Stdout);
The next thing is the advantage of using the freopen () function. We do not need to modify scanf and printf, but maintainCode. Because the freopen () function redirects the standard stream and points it to the previously specified file, saving time and effort. Like...
Finally, you only need to use fclose to close the input and output files.
Fclose(Stdin);
Fclose(Stdout);
To restore the handle, you can re-open the standard console device file, but the name of the device file is related to the operating system.
DOS/win:
Freopen("Con", "R",Stdin);
Linux:
Freopen("/Dev/console", "R",Stdin);
Add a code template:
# Include < Stdio. h >
Int Main ()
{
Freopen ( " Slyar. In " , " R " , Stdin );
Freopen ( " Slyar. Out " , " W " , Stdout );
/**/ /*Write code as is in the middle, and do not need to modify anything*/
Fclose (stdin );
Fclose (stdout );
Return 0 ;
}
PS. one problem just found is that when compiling the source code containing file operations with C-free, you must put fopen or freopen under the definition of all variables; otherwise, the compilation will be wrong... bytes
From: http://www.slyar.com/blog/c-freopen-stdin-stdout.html