标准输入输出重定向

xiaoxiao2021-02-27  312

方法1:

//使用freopen_s()函数 #include <stdio.h> int main() { //将控制台的标准输入输出改成从文件中读取写入 FILE *pFileRead ; FILE *pFileWrite; FILE *pStdint; pStdint = stdin; FILE *pStdout; pStdout = stdout; errno_t err; printf( "将控制台的标准输入输出改成从文件中读取写入\n"); err = freopen_s(&pFileRead, "infile.txt", "r", stdin); if (err != 0) { printf( "pFileRead错误freopen\n"); return 0; } err = freopen_s(&pFileWrite, "outfile.txt", "w", stdout); if (err != 0) { printf( "pFileWrite错误freopen\n"); return 0; } int n; while (scanf_s("%d", &n) != EOF) { n *= 2; printf("%d\n", n); } printf("结束01 结束输出\n"); //回到到控制台的标准输入输出 windows为"CON" linux为"/dev/console" err = freopen_s(&pStdint, "CON", "r", pFileRead); if (err != 0) { printf("pStdout错误freopen\n"); fclose(pFileRead); fclose(pFileWrite); return 0; } err = freopen_s(&pStdout, "CON", "w", pFileWrite); if (err != 0) { printf( "pStdout错误freopen\n"); fclose(pFileRead); fclose(pFileWrite); return 0; } printf( "结束02 输入0表示结束---\n"); do{ scanf_s("%d", &n); } while (n != 0); fclose(pFileRead); fclose(pFileWrite); return 0; }

//------------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------------

方法2:

//使用ifstream和ofstream及cin和cout的rdbuf() #include"stdafx.h" #include <iostream> #include <fstream> using namespace std; int main() { printf(" 使用ifstream和ofstream及cin和cout的rdbuf()来改变控制台的标准输入输出\n"); printf(" --by MoreWindows( http://blog.csdn.net/MoreWindows )--\n\n"); //将控制台的标准输入输出改成从文件中读取写入 ifstream inFile("infile.txt"); ofstream outFile("outfile.txt"); //保存原来的输入输出方式 streambuf类就是basic_streambuf类 streambuf *strmin_buf = cin.rdbuf(); streambuf *strmout_buf = cout.rdbuf(); printf("开始处理文件\n....\n"); //重定向到文件 cin.rdbuf(inFile.rdbuf()); cout.rdbuf(outFile.rdbuf()); //原程序代码 int n; while (cin >> n) { n *= 2; cout << n << endl; } inFile.close(); outFile.close(); //回到控制台的标准输入输出 cin.rdbuf(strmin_buf); cout.rdbuf(strmout_buf); cout << "文件已经处理完毕 输入0表示结束:" << endl; do{ cin >> n; } while (n != 0); return 0; }

转载请注明原文地址: https://www.6miu.com/read-4084.html

最新回复(0)