gpt4 book ai didi

c++ - 使用 fstream 在 C++ 中读取和写入二进制文件

转载 作者:太空狗 更新时间:2023-10-29 19:48:30 25 4
gpt4 key购买 nike

我正在尝试编写简单的 C++ 代码来读写文件。问题是我的输出文件比原始文件小,我一直在寻找原因。我有一个 6.6 kb 的图像,我的输出图像大约是 6.4 kb

#include <iostream>
#include <fstream>

using namespace std;

ofstream myOutpue;
ifstream mySource;

int main()
{

mySource.open("im1.jpg", ios_base::binary);
myOutpue.open("im2.jpg", ios_base::out);

char buffer;

if (mySource.is_open())
{
while (!mySource.eof())
{
mySource >> buffer;
myOutpue << buffer;
}
}

mySource.close();
myOutpue.close();

return 1;
}

最佳答案

为什么不只是:

#include <fstream>

int main()
{
std::ifstream mySource("im1.jpg", std::ios::binary);
std::ofstream myOutpue("im2.jpg", std::ios::binary);
myOutpue << mySource.rdbuf();
}

或者,不那么喋喋不休:

int main()
{
std::ofstream("im2.jpg", std::ios::binary)
<< std::ifstream("im1.jpg", std::ios::binary).rdbuf();
}

关于c++ - 使用 fstream 在 C++ 中读取和写入二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23471534/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com