将内容从 C 文件传输到C++流
Transfer contents from C FILE to C++ stream
>假设我用 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++流(如stringstream
甚至std::cout
)中复制该文件的内容。我该怎么做?
您可以使用
ifstream
和rdbuf()
:
#include <fstream>
#include <sstream>
std::ifstream in("whatever.txt");
std::ostringstream s;
s << in.rdbuf();
或:
std::ifstream in("whatever.txt");
std::cout << in.rdbuf();
您已打开文件进行写入。无论如何,您都需要关闭它并重新打开它,您也可以随心所欲地打开它(如果您愿意,可以作为 istream)。然后,这仅取决于您对性能的关心程度。如果你真的关心,你应该分块读取它(一次至少 512 字节)。如果你不关心性能,你可以读取一个字节,吐出一个字节。
先关闭它。
fclose(fp);
然后再次打开
string line;
ifstream myfile ("whatever.txt");
if (myfile.is_open())
{
while ( myfile.good() )
{
getline (myfile,line);
cout << line << endl;
}
myfile.close();
}
相关文章:
- 通过套接字[TCP]传输数据 如何在C / C ++中打包多个整数并使用send() recv()传输数据
- Angelscript从C++传输数组
- 如何将图像传输到c++(dll)中的缓冲区,然后在c#的缓冲区中读/写
- 从服务器传输到客户端的消息不会出现
- USB传输的LibUSB C++格式不同
- 在本地网络中通过OpenCV(C++)实时流式传输图像
- 将相机数据从服务器实时流式传输到客户端
- 加密在 Windows、C++ 和 Java 中传输中的数据
- 如何从网站获取数据并将其传输到数据库?
- 使用蓝牙组件将数据从Android手机传输到串行设备时出现问题
- 在 OpenCV 中应用公式并传输图像
- 在不传输的情况下更改 Win32 中的串行端口波特率
- Vulkan 的传输队列系列功能和显卡支持:条件检查是否准确?
- 如何使用CAPL的诊断功能获取CAN传输的数据(256字节)?
- 如何通过ROS将realsense数据传输到其他设备
- 将音频从浏览器流式传输到WebRTC本机C++应用程序
- 将FFMpeg AVFrame对象从C++应用程序流式传输到Python的最佳方法?
- 使用IMFSourceReader(Microsoft媒体基金会)进行音频流传输
- 在PROGMEM中添加更多数据会中断Arduino Mega 2560上的SPI传输
- QTcpSocket 在 RemoteHostClosedError 后重新连接到服务器时无法传输数据