File input and output (1): Redirection, file input and output redirection
Function Name: freopen Declaration: FILE * freopen (const char * path, const char * mode, FILE * stream); FILE: stdio. h parameter description: path: file name, used to store the custom file name of input and output. Mode: the mode in which the file is opened. The mode is the same as that in fopen (such as r-read-only and w-write. Stream: a file, usually using a standard stream file. Return Value: success. A pointer to the file specified by path is returned. If no pointer is returned, NULL is returned. (Generally, you do not need to use its return value) function: Implements redirection to direct a predefined standard stream file to a file specified by path. Standard stream files refer to stdin, stdout, and stderr. Stdin is the standard input stream, the default is the keyboard; stdout is the standard output stream, the default is the screen; stderr is the standard error stream, generally set the screen as the default.
Freopen ("debug \ in.txt", "r", stdin) redirects the standard input stream stdin to the debug \ release file to obtain the input. You only need to paste the input data to in.txt first, which makes debugging much easier. Similarly, freopen ("debug \ out.txt", "w", stdout) is used to redirect stdout to the debug \ out.txt file. In this example, open the out.txt file to view the output result. Note:
In freopen ("debug \ in.txt", "r", stdin.pdf, place the input file in.txt in the folder debug. The folder debug is the debugging folder automatically generated when the project file is created in VC. If you change to freopen ("in.txt", "r", and stdin.pdf, The in.txt file will be placed in the created project folder. The in.txt file can also be placed in other folders, and the path can be correctly written.
The following code gets the variable from the file and inputs the sum of the two into another file:
# Include <iostream>
# Include <cstdio>
Using namespace std;
Int main ()
{
Freopen ("input.txt", "r", stdin );
Freopen ("output.txt", "w", stdout );
Int a, B;
While (cin> a> B ){
Cout <a + B <endl;
}
Fclose (stdin );
Fclose (stdout );
Return 0;
}