从32位和64位的二进制文件读取

时间:2014-03-28 09:38:37

标签: c++ c

我们正在创建一个用作校验和的二进制文件。我们使用bitset库函数来执行此操作。我们遇到这样一种情况,即在32位操作系统上创建的文件在64位操作系统上无法使用或无法读取。

/***** Code to generate the binary file ******/
#define PB_BITSET_SIZE 32
std::bitset <PB_BITSET_SIZE> m_bitset;
//wstrFileName contains the path to the binary file
FILE *stream = _wfopen (wstrFileName.c_str(), L"wb");

if (!stream) 
    throw std::wstring (L"Opening file failed");

    size_t writeCount = 0;
 // get number of bits set
    size_t bitCount = m_bitset.count();


    // write number of bits set
     writeCount = fwrite(&bitCount, sizeof (size_t), 1, stream);
     if (writeCount != 1) 
     throw std::wstring (L"Writing checksum to file failed");

    // get bitset as unsigend long
     unsigned long bitSetLongValue = m_bitset.to_ulong();

     writeCount = fwrite(&bitSetLongValue, sizeof (unsigned long), 1, stream);

     if (writeCount != 1) 
    throw std::wstring (L"Writing bitset to file failed");

     fclose(stream);
     stream = NULL;


/***************Code to read the binary file ******************/

FILE * stream = NULL;
    size_t bitCount = m_bitset.count();
    unsigned long bitSetLongValue = m_bitset.to_ulong();
    wstring  wstrFileName(L"D:\\Temp\\ECO\\opt.dat");

    stream = _wfopen (wstrFileName.c_str(), L"rb");

        if (!stream) 
            throw std::wstring (L"Opening file failed");

        size_t readCount = 0;

        // read number of bits set


        readCount = fread(&bitCount, sizeof (size_t), 1, stream);

        if (readCount != 1) throw std::wstring (L"Reading checksum from file failed");

        // read bitset as unsigend long


        readCount = fread(&bitSetLongValue, sizeof (unsigned long), 1, stream);
                    if (readCount != 1) *throw std::wstring (L"Reading bitset from file failed");*

        fclose(stream);
        stream = NULL;

        m_bitset = bitSetLongValue;

        // check integrity of file 
        if (m_bitset.count() != bitCount) throw std::wstring (L"Invalid checksum");

当我们尝试在64位操作系统上读取文件时,我们收到错误从文件读取bitset失败

2 个答案:

答案 0 :(得分:3)

如果您不是100%确定sizeof(whatever)总是大小相同 - 在所有平台,编译器(及其配置),架构......上,请不要依赖whatever。< / p>

使用int16_t中的int32_tuint64_t<stdint.h>等类型代替size_tunsigned long

请在此处查看不同平台上的字体大小比较:http://en.cppreference.com/w/cpp/language/types

答案 1 :(得分:2)

sizeof (unsigned long)
嗯,匆匆看一眼这可能是一个问题,64位机器上有8个,32位机器上有4个。