C 解析 bin 文件
#include <stdio.h>
int main() {
FILE *file;
file = fopen("example.bin", "rb");
if (file == NULL)
{
printf("无法打开文件\n");
return -1;
}
int num;
while(fread(&num, sizeof(int), 1, file))
{
printf("%d ", num);
}
fclose(file);
return 0;
}
C++ 存储和解析 bin 文件
#include <iostream>
#include <fstream>
using namespace std;
int main() {
int num = 10;
float pi = 3.1415926;
ofstream file("data.bin", ios::binary);
if (file)
{
file.write(reinterpret_cast<char*>(&num), sizeof(num));
file.write(reinterpret_cast<char*>(&pi), sizeof(pi));
file.close();
cout << "成功保存数据到二进制文件!" << endl;
}
else
{
cerr << "无法打开或创建文件!" << endl;
return -1;
}
ifstream inputFile("data.bin", ios::binary);
if (inputFile)
{
int readNum;
float readPi;
inputFile.read(reinterpret_cast<char*>(&readNum), sizeof(readNum));
inputFile.read(reinterpret_cast<char*>(&readPi), sizeof(readPi));
inputFile.close();
cout << "从二进制文件中读取到的数据为:" << endl;
cout << "整型变量:" << readNum << endl;
cout << "浮点型变量:" << readPi << endl;
}
else
{
cerr << "无法打开二进制文件!" << endl;
return -1;
}
return 0;
}