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++读写进制文件的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程