我有一个充满整数的大文件,我正在加载.我刚刚开始使用C++,我正在尝试文件流的东西.从我读过的所有内容看来,我只能读取字节数,因此我必须设置一个char数组,然后将其转换为int指针.
有没有一种方法可以一次读取4个字节,并且不需要char数组?
const int HRSIZE = 129951336; //The size of the table
char bhr[HRSIZE]; //The table
int *dwhr;
int main()
{
ifstream fstr;
/* load the handranks.dat file */
std::cout << "Loading table.dat...\n";
fstr.open("table.dat");
fstr.read(bhr, HRSIZE);
fstr.close();
dwhr = (int *) bhr;
}
Run Code Online (Sandbox Code Playgroud)
Yac*_*oby 16
要读取单个整数,请将整数的地址传递给read函数,并确保只读取sizeof int字节.
int myint;
//...
fstr.read(reinterpret_cast<char*>(&myint), sizeof(int));
Run Code Online (Sandbox Code Playgroud)
您可能还需要以二进制模式打开文件
fstr.open("table.dat", std::ios::binary);
Run Code Online (Sandbox Code Playgroud)