查看代码
#include <fstream>
#include <iostream>
#include <iomanip>
//#include "flow.h"
unsigned char buf[2048];
unsigned char flow[10];
void read_f(){
// 读文件的十六进制并保存到文件中
size_t ret;
// rb是读二进制
FILE *fp = fopen("./hello.exe", "rb");
if (fp == nullptr) return;
// wb是写二进制
// 因为要保存二进制,所以不以二进制方式写
FILE *fp2 = fopen("./flow.h", "w");
if (fp2 == nullptr) return;
int sz = 0;
while ((ret = fread(buf, 1, 2048, fp))) {
printf("%llu\n", ret);
// C语言文件拷贝 通过文件io的方式实现
// fwrite(buf, 1, ret, fp2);
for (int i = 0; i < ret; i++) {
fprintf(fp2, "0x%02x, ", (unsigned char)buf[i]);
if (sz % 8 == 7) fprintf(fp2, "\n");
sz++;
}
}
fclose(fp);
fclose(fp2);
}
// size : 2447825
// 将十六进制写回成文件
// C++
void write_f() {
std::ofstream out("./copy.exe", std::ios::binary);
// for (int i = 0; i < 2447825; i++) out << flow[i];
out.write((char *)flow, 2447825);
out.flush();
out.close();
}
void copy_f() {
// C++ 文件拷贝
std::ifstream in("./hello.exe", std::ios::binary);
std::ofstream out("./copy.exe", std::ios::binary);
if (!in.is_open()) return;
if (!out.is_open()) return;
out << in.rdbuf();
in.close();
out.close();
}
void read_f_cpp() {
// C++ 将文件保存为二进制
std::ifstream in("./hello.exe", std::ios::binary);
std::ofstream out("./flow.h", std::ios::out);
if (!in.is_open()) return;
if (!out.is_open()) return;
unsigned int sz = 0;
while (in.read((char *)buf, 2048)) {
std::streamsize num = in.gcount();
for (std::streamsize i = 0; i < num; i++) {
out << "0x" << std::setw(2) << std::setfill('0') << std::hex << (unsigned)buf[i] << ", ";
if (i % 8 == 7) out << std::endl;
sz++;
}
}
in.close();
out.close();
}
int main() {
// read_f();
// write_f();
// copy_f();
read_f_cpp();
return 0;
}