以32位二进制数据c ++读取文件

时间:2014-06-16 22:19:40

标签: c++ io

我需要以二进制数据的形式读取文件,确保文件是偶数个32位字(如果需要,我可以添加0的填充字节)。

我已经摆弄了ios :: binary,但是我有什么东西不见了?例如:

string name1 = "first", name2 = "sec", name3 = "third";
int j = 0, k = 0;
ifstream ifs(name1.c_str());
ifs >> j; 
ifs.close();

这是我需要利用的吗?我对这门语言很陌生。

2 个答案:

答案 0 :(得分:0)

std::ifstream ifs(name1.c_str(), std::ifstream::binary);
if (!ifs)
{
    // error opening file
}
else
{
    int32_t j;
    do
    {
        j = 0;
        ifs.read(&j, sizeof(j));
        if (ifs)
        {
            // read OK, use j as needed
        }
        else
        {
            if (ifs.eof())
            {
                // EOF reached, use j padded as needed
            }
            else
            {
                // error reading from file
            }

            break;
        }
    }
    while (true);

    ifs.close();
}

答案 1 :(得分:0)

我能够使用与Remy Lebeau类似的方法读取32位。此代码与C ++ 03兼容。

#include <stdint.h>
#include <fstream>

// Rest of code...

std::ifstream file(fileName, std::ifstream::in | std::ifstream::binary | std::ifstream::beg);

int32_t word;
if(!file){
    //error
} else {
    while(file.is_open()){
        if(file.eof()){ printf("END\n"); break; }

        word = 0;
        file.read((char*)&word,sizeof(word));

        //Do something
        printf("%d\n",word);
    }
}

请注意,如果文件的精确增量不是32,我不会添加填充。如果添加该功能,我将更新代码。