freopen function:
Using a different file or reopen the flow pattern, i.e. redirection
C++
//把一个字符串写入到文件中去: #include<iostream> using namespace std; int main(void) { /* redirect standard output to a file */ if(freopen("D:\\out.txt", "w", stdout) == NULL) fprintf(stderr,"error redirecting stdout\n"); /* this output will go to a file */ printf("This will go into a file.\n"); string s = "12345"; cout<<s<<endl; int a,b; while(cin>>a>>b){ cout<<a<<b<<endl; } /*close the standard output stream*/ fclose(stdout); return 0; }
#include <the iostream> the using namespace STD; int main ( void ) { the FILE * FP; FP = The freopen ( " D: \\ in.txt " , " R & lt " , stdin); // The freopen () return value, if establish a connection to the file fails, return NULL IF (FP = NULL!) { // file connection is established int C; CIN >> C; // read data from a file COUT C << << endl; // in the display data on the screen } the else { COUT << "Open Error"<<endl; } //输出到控制台“CON” fp = freopen("CON","r",stdin); int a, b; cin>>a>>b; cout<<a<<b<<endl<<endl; return 0; }
#include<iostream> using namespace std; int main() { freopen("D:\\in.txt", "r", stdin); freopen("D:\\out.txt", "w", stdout); int a, b; while (cin >> a >> b) cout << a + b << endl; fclose(stdin); fclose(stdout); return 0; }
#include<iostream> using namespace std; int main() { int a, b; freopen("D:\\in.txt", "r", stdin); freopen("D:\\out.txt", "w", stdout); while (scanf("%d%d", &a, &b) == 2) printf("%d\n", a + b); fclose(stdin); fclose(stdout); return 0; }
#include<iostream> using namespace std; int main() { int a, b; freopen("D:\\in.txt", "r", stdin); freopen("D:\\out.txt", "w", stdout); while (scanf("%d%d", &a, &b) == 2) printf("%d\n", a + b); //fclose(stdin); //fclose(stdout); freopen("CON", "r", stdin); freopen("CON", "w", stdout); printf("Hello World\n"); scanf("%d%d", &a,&b); return 0; }
#include<iostream> using namespace std; int main() { int a, b; freopen("D:\\in.txt", "r", stdin); freopen("D:\\out.txt", "w", stdout); while (scanf("%d%d", &a, &b) == 2) printf("%d\n", a + b); //fclose(stdin); //fclose(stdout); freopen("CON", "r", stdin); freopen("CON", "w", stdout); printf("Hello World\n"); scanf("%d%d", &a,&b); return 0; }
It should be noted, in fact, there is not really close, just redirects again, back to the console.
After windows / DOS, file read freopen ( " CON ", " r " , stdin), after writing a file freopen ( " CON ", " w " , stdout).
In linux, console devices is / dev / console: freopen ( "/ dev / console", "r", stdin).