C++读写进制文件
2022/1/25 14:04:35
本文主要是介绍C++读写进制文件,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
#include <iostream> #include <fstream> using namespace std; int main() { // //char path[] = R"(D:\Code\read\unet.bin)"; ifstream fin; ofstream fout; fin.open(R"(unet.bin)", ios::binary); //ofstream ouF; /*ouF.open(R"(unet.bin)", std::ofstream::binary); ouF.write(reinterpret_cast<const char*>(fin), sizeof(int) * 5); ouF.close();*/ // /*if (!fin) { cout << "open error!" << endl; return 0; }*/ // 将读写位置移动到文件末尾,获取文件大小 /*ifstream fin(R"(unet.bin)", ios::binary);*/ fin.seekg(0, ios_base::end); long long firm_len = fin.tellg(); cout << "size of firm: " << firm_len << endl; // 将读写位置移动到文件开头,申请内存,将固件内容存入 Buffer fin.seekg(0, ios_base::beg); auto* Buffer = new char[firm_len]; fin.read((char*)Buffer, sizeof(char) * firm_len); /* for (int i = 0; i < firm_len;i++) { if (i % 16 != 0) { printf(" "); printf("%02X", (unsigned char)Buffer[i]); } if (i % 16 == 0) { printf("\n"); } }*/ cout << "size of firm: " << firm_len << endl; /* for (int i = 0; i < firm_len; i++) { }*/ fout.open(R"(unet-out2.bin)", ios::binary); fout.write((char*)Buffer, sizeof(char) * firm_len); delete[] Buffer; } //#include <iostream> //#include <fstream> //using namespace std; // //int main() { // filebuf* pbuf; // ifstream filestr; // long size; // char* buffer; // // 要读入整个文件,必须采用二进制打开 // filestr.open("unet.bin", ios::binary); // // 获取filestr对应buffer对象的指针 // pbuf = filestr.rdbuf(); // // // 调用buffer对象方法获取文件大小 // size = pbuf->pubseekoff(0, ios::end, ios::in); // pbuf->pubseekpos(0, ios::in); // // // 分配内存空间 // buffer = new char[size]; // // // 获取文件内容 // pbuf->sgetn(buffer, size); // // filestr.close(); // // 输出到标准输出 // cout.write(buffer, size); // cout << "size of firm: " << endl; // // delete[]buffer; // return 0; //} //
这篇关于C++读写进制文件的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15PingCAP 黄东旭参与 CCF 秀湖会议,共探开源教育未来
- 2024-05-13PingCAP 戴涛:构建面向未来的金融核心系统
- 2024-05-09flutter3.x_macos桌面os实战
- 2024-05-09Rust中的并发性:Sync 和 Send Traits
- 2024-05-08使用Ollama和OpenWebUI在CPU上玩转Meta Llama3-8B
- 2024-05-08完工标准(DoD)与验收条件(AC)究竟有什么不同?
- 2024-05-084万 star 的 NocoDB 在 sealos 上一键起,轻松把数据库编程智能表格
- 2024-05-08Mac 版Stable Diffusion WebUI的安装
- 2024-05-08解锁CodeGeeX智能问答中3项独有的隐藏技能
- 2024-05-08RAG算法优化+新增代码仓库支持,CodeGeeX的@repo功能效果提升