ofstream写入图片
时间: 2023-10-06 22:06:12 浏览: 216
使用 ofstream 写入图片需要先将图片以二进制方式读入内存,然后再将内存中的数据写入到文件中。
以下是一个简单的示例代码:
```c++
#include <fstream>
#include <iostream>
int main() {
// 以二进制方式读取图片
std::ifstream input("example.jpg", std::ios::binary);
if (!input) {
std::cerr << "Failed to open file for reading!\n";
return 1;
}
// 获取文件长度
input.seekg(0, std::ios::end);
std::size_t size = input.tellg();
// 读取文件内容到内存
char* buffer = new char[size];
input.seekg(0, std::ios::beg);
input.read(buffer, size);
input.close();
// 写入文件
std::ofstream output("example_copy.jpg", std::ios::binary);
if (!output) {
std::cerr << "Failed to open file for writing!\n";
return 1;
}
output.write(buffer, size);
output.close();
delete[] buffer;
std::cout << "Done!\n";
return 0;
}
```
该示例代码中,我们先使用 `std::ifstream` 以二进制方式打开要写入的图片文件。接着,我们使用 `seekg` 和 `tellg` 获取文件长度,并将文件内容读取到内存中。最后,我们使用 `std::ofstream` 将内存中的数据写入到新的文件中。
阅读全文
相关推荐


















