C/C++ 文件IO 拷贝文件,将二进制文件写为十六进制

#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("./4.png", "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("./4.png", std::ios::binary);
    std::ofstream out("./copy.png", 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("./4.png", 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.eof()) {
        in.read((char *)buf, 2048);
        std::streamsize num = in.gcount();
        std::cout << num << std::endl;
        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;
}

 

原文链接: https://www.cnblogs.com/correct/p/17082316.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    C/C++ 文件IO 拷贝文件,将二进制文件写为十六进制

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/315222

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月16日 下午1:40
下一篇 2023年2月16日 下午1:42

相关推荐