一次读取4个字节

oad*_*ams 7 c++

我有一个充满整数的大文件,我正在加载.我刚刚开始使用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)

  • +1代替C++答案而不是不安全的C风格演员表 (6认同)
  • 它在运行时同样安全,但在截止日期前的星期天晚上阅读代码时更安全. (4认同)
  • @Daniel:`reinterpret_cast`并不比C风格的演员更"安全". (2认同)
  • 如果要读取原始整数,则需要处理endian问题.一种技术是以网络端序存储,这意味着你在写之前使用`htonl`,在读取之后使用`ntohl`. (2认同)