GPT答: |
7i24.cn
|
下面给出一个实现可靠读取bin文件,将其存储在char数组变量中的例子:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
// 定义一个文件流
ifstream myfile;
// 打开要读取的bin文件
myfile.open("example.bin");
// 如果文件打开成功
if (myfile.is_open())
{
// 使用文件大小获取bin文件中数据的大小
int size = myfile.tellg();
// 分配内存空间,用来存储文件中的字符
char *buffer = new char[size];
// 读取文件中的数据,存储到buffer中
myfile.read(buffer, size);
// 输出buffer中的数据
cout << "The data read from the binary file is: " << endl;
cout << buffer << endl;
// 释放buffer所占用的内存空间
delete [] buffer;
buffer = NULL;
// 关闭文件
myfile.close();
}
else
{
// 打开文件失败时,显示以下信息
cout << "Error opening file" << endl;
}
return 0;
}
|