一次读取4个字节

时间:2010-06-04 13:40:49

标签: 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;    
}

5 个答案:

答案 0 :(得分:16)

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

int myint;

//...

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

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

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

答案 1 :(得分:4)

要从ifstream读取4个字节,您可以按如下方式重载operator>>(它实际上是basic_istream类模板的部分特化,因此istream_iterator可以使用{{从它开始。这里使用类operator>>来继承它的所有输入文件流功能):

basic_ifstream

然后您可以通过以下方式使用它:

#include <fstream>

typedef unsigned int uint32_t;    
struct uint32_helper_t {};

namespace std {
template<class traits>
class basic_istream<uint32_helper_t, traits> : public basic_ifstream<uint32_t> {
public:
    explicit basic_istream<uint32_helper_t, traits>(const char* filename, 
        ios_base::openmode mode ) : basic_ifstream<uint32_t>( filename, mode ) {}

    basic_istream<uint32_helper_t, traits>& operator>>(uint32_t& data) {
        read(&data, 1);
        return *this;
    }
};
} // namespace std {}

答案 2 :(得分:1)

你可以这样做:

int i;
fstr.read((int*)&i, sizeof(int));

答案 3 :(得分:0)

这是什么意思?顺便说一句,您的代码(以及此代码)假定数据的本机字节序。

const int HRSIZE = 129951336;  //The size of the table
int dhr[HRSIZE/sizeof(int)];   //The table

int main()
{
    ifstream fstr;

    /* load the handranks.dat file */
    std::cout << "Loading table.dat...\n";
    fstr.open("table.dat");
    fstr.read((char*)dhr, HRSIZE);
    fstr.close();
}

答案 4 :(得分:0)

你可以试试这个:

const int HRSIZE = 129951336/sizeof(int);  //The size of the table
int bhr[HRSIZE];   //The table

int main(int argc, char *argv[])
{
    ifstream fstr;

    /* load the handranks.dat file */
    std::cout << "Loading table.dat...\n";
    fstr.open("table.dat");
    for (int i=0; i<HRSIZE; ++i)
    {
        fstr.read((char *)(bhr+i), sizeof(int));
    }
    fstr.close();

    // for correctness
    return 0;
}
相关问题