一次读取4个字节 [英] Reading in 4 bytes at a time

查看:352
本文介绍了一次读取4个字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大文件,其中加载了整数,我刚刚开始使用C + +,我正在试验filestream的东西。从我读过的一切,看来我只能读取字节,所以我必须设置一个字符数组,然后将其作为一个int指针。

I have a big file full of integers that I'm loading in. I've just started using C++, and I'm trying out the filestream stuff. From everything I've read, it appears I can only read in bytes, So I've had to set up a char array, and then cast it as a int pointer.

是否有一种方法可以一次以4个字节读取,并且不需要char数组?

Is there a way I can read in 4 bytes at a time, and eliminate the need for the char array?

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


推荐答案

将整数的地址传递给读取函数,并确保只读取 sizeof int 字节。

To read a single integer, pass in the address of the integer to the read function and ensure you only read sizeof int bytes.

int myint;

//...

fstr.read(reinterpret_cast<char*>(&myint), sizeof(int));

您可能还需要以二进制模式打开文件

You may also need to open the file in binary mode

fstr.open("table.dat", std::ios::binary);

这篇关于一次读取4个字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆