C++ 中的 I/O 重定向
在 C 中,我们可以使用 freopen() 函数进行重定向。使用此函数,我们可以将现有 FILE 指针重定向到另一个流。freopen 的语法如下
FILE *freopen(const char* filename, const char* mode, FILE *stream)
同样地,在 C++ 中,我们也可以进行重定向。在 C++ 中,使用流。这里我们可以使用我们自己的流,也可以重定向系统流。在 C++ 中,有三种类型的流。
- istream:只能支持输入的流
- ostream:只能支持输出的流
- iostream:这些可以用于输入和输出。
这些类和文件流类衍生自 ios 和 stream-buf 类。因此,文件流和 IO 流对象的行为类似。C++ 允许将流缓冲区设置为任何流。因此,我们可以简单地更改与流关联的流缓冲区进行重定向。例如,如果有两个流 A 和 B,并且我们要将流 A 重定向到流 B,我们需要按照以下步骤进行操作
- 获取流缓冲区 A 并存储
- 将流缓冲区 A 设置为另一个流缓冲区 B
- 将流缓冲区 A 重置为其先前位置(可选)
示例代码
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main() {
fstream fs;
fs.open("abcd.txt", ios::out);
string lin;
// Make a backup of stream buffer
streambuf* sb_cout = cout.rdbuf();
streambuf* sb_cin = cin.rdbuf();
// Get the file stream buffer
streambuf* sb_file = fs.rdbuf();
// Now cout will point to file
cout.rdbuf(sb_file);
cout << "This string will be stored into the File" << endl;
//get the previous buffer from backup
cout.rdbuf(sb_cout);
cout << "Again in Cout buffer for console" << endl;
fs.close();
}输出
Again in Cout buffer for console
abcd.txt
This string will be stored into the File
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP