读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;