Had*_*ekh 2 c++ binary fstream file
我正在尝试编写一个c ++代码来读取文件并将其编码为(1/0)二进制文件,然后从(1/0)文件中获取原始文件.我必须从其他计算机中的1/0二进制文件重建原始文件,因此1/0以及如何重建它对我来说非常重要.
原因是,我的输出文件小于原始文件.例如,如果我有一个6.6 kb的jpeg图像,重建的文件大约是6.4 kb.
#include <iostream>
#include <fstream>
#include <bitset>
using namespace std;
ofstream myOutput;
ifstream mySource;
int main()
{
mySource.open("im1.jpg", ios_base::binary);
myOutput.open("im2.jpg", ios_base::binary);
unsigned char buffer;
unsigned char recBuffer;
unsigned int ascii;
if (mySource.is_open())
{
while (!mySource.eof())
{
// code
mySource >> buffer;
ascii = static_cast<unsigned int>(buffer);
cout<< bitset<8>(ascii) << endl;
// reconstruction
recBuffer = static_cast<char>(ascii);
myOutput << recBuffer;
}
}
mySource.close();
myOutput.close();
return 1;
}
Run Code Online (Sandbox Code Playgroud)
我能想到的最天真的解决方案可能如下所示:
#include <fstream>
int main()
{
std::ifstream mySource("im1.jpg", std::ios::binary);
std::ofstream myOutput("im2.jpg", std::ios::binary);
for (char c; mySource.get(c); )
{
std::cout << static_cast<unsigned int>(static_cast<unsigned char>(c)) << "\n";
myOutput.put(c);
}
}
Run Code Online (Sandbox Code Playgroud)
严格来说,您也应该检查写入错误:
if (!myOutput.put(c))
{
std::cerr << "Write error!\n";
break;
}
Run Code Online (Sandbox Code Playgroud)