c++ - 将内容从 C FILE 传输到 C++ 流

标签 c++ file-io ostream

<分区>

假设我用 C 语法打开了一个文件

FILE* fp = fopen("whatever.txt", "w");
// Library function needs FILE* to work on
libray_function(fp);

// Now I'd like to copy the contents of file to std::cout
// How???

fclose(fp);

我希望能够在 C++ ostream 中复制该文件的内容(如 stringstream 或什至 std::cout)。我该怎么做?

最佳答案

你可以使用 ifstreamrdbuf() :

#include <fstream>
#include <sstream>

std::ifstream in("whatever.txt");
std::ostringstream s;
s << in.rdbuf();

或:

std::ifstream in("whatever.txt");
std::cout << in.rdbuf();

关于c++ - 将内容从 C FILE 传输到 C++ 流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12583615/

相关文章:

c++ - 如何在cpp中返回十进制值

c++ - 为什么这里模板 Vector3<int> 不能转换为 Vector3<int>?

c++ - 使用 map 容器的字母频率

c - epoll 文件描述符操作

python - 使用 for 循环读取文件时跳过一行

c++ - 为什么 ostream::operator<< 是 char 参数的全局函数?

c++ - 与解析相关的 token 到底是什么

c++ - 我应该让我的 MutexLock 易变吗?

c++ - 如果没有 endl,则重载 ostream 运算符段错误

java - 在 Java 中使用并发在磁盘上创建键值存储