bin文件读写

读bin文件

方法一:

int getBinSize(char *path)
{
    int  size = 0;
    FILE  *fp = fopen(path, "rb");
    if (fp)
    {
        fseek(fp, 0, SEEK_END);
        size = ftell(fp);
        fclose(fp);
    }
    printf("\npath=%s,size=%d \n", path, size);
    return size;
}
 
void readBin(char *path, char *buf, int size)
{
    FILE *infile;
 
    if ((infile = fopen(path, "rb")) == NULL)
    {
        printf("\nCan not open the path: %s \n", path);
        exit(-1);
    }
    fread(buf, sizeof(char), size, infile);
    fclose(infile);
}

方法二: 

void getBinSize(std::string path)
{
    int size = 0;
    std::ifstream infile(path, std::ifstream::binary);
    
    infile.seekg(0, infile.end);
    int size= infile.tellg();
    infile.seekg(0, infile.beg);
    
    infile.close();
    printf("\npath=%s,size=%d \n", path, size);
    return size;
}
 
void readBin(std::string path, char *buf, int size)
{
  std::ifstream infile(path, std::ifstream::binary);
 
  infile.read(static_cast<char *>(buf), size);
  infile.close();
}

写bin文件

方法一:

void writeBin(char *path, char *buf, int size)
{
    FILE *outfile;
 
    if ((outfile = fopen(path, "wb")) == NULL)
    {
        printf("\nCan not open the path: %s \n", path);
        exit(-1);
    }
    fwrite(buf, sizeof(char), size, outfile);
    fclose(outfile);
}

方法二:

/// C++ 保存bin文件
void writeBin(std::string path, char *buf, int size)
{
  std::ofstream outfile(path, std::ifstream::binary);
 
  outfile.write((char *)(buf), size);
 
  outfile.close();
}

调用

方法一:

// read binFile
char filePath[] = "./demo.bin";
int size = GetBinSize(filePath);
char *buf = (char*)malloc(size);
readBin(filePath, buf, size);
float *fbuf = (float*)buf;
 
// write binFile
char saveFilePath[] = "./demo_saved.bin"
writeBin(saveFilePath, buf, size)
 
free(buf)

方法二: 

// read binFile
std::string filePath= "./demo.bin";
int size = GetBinSize(filePath);
char *buf= new char[size];
readBin(filePath, buf, size);
float *fbuf = reinterpret_cast<float *>(buf);
 
// write binFile
std::string saveFilePath= "./demo_saved.bin";
writeBin(saveFilePath, buf, size);
 
delete buf;

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值