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

Read file in as 32 bit binary data c++

本文关键字:数据 c++ 二进制 32位 文件 读取      更新时间:2023-10-16

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

我已经摆弄了ios::二进制,但有什么我错过了?例如:

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

这是我需要利用的东西吗?我对这门语言相当陌生

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

我能够使用与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("ENDn"); break; }
        word = 0;
        file.read((char*)&word,sizeof(word));
        //Do something
        printf("%dn",word);
    }
}

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