sameer karjatkar
sameer karjatkar

Reputation: 2057

Reading from a binary file on 32-bit and 64-bit

We are creating a binary file which is used as a checksum . We use the bitset library functions to do this . We have a situation wherein a file created on 32 bit os , is not usable or not readable on 64-bit Os .

/***** 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");

When we try to read the file on a 64-bit OS , we get the error Reading bitset from file failed

Upvotes: 0

Views: 2753

Answers (2)

Messa
Messa

Reputation: 25181

Don't rely on sizeof(whatever) if you are not 100% sure that whatever has always the same size - on all platforms, compilers (and their configuration), architectures...

Use types like int16_t, int32_t, uint64_t from <stdint.h> for this instead of size_t or unsigned long.

See comparison of type sizes on different platforms here: http://en.cppreference.com/w/cpp/language/types

Upvotes: 3

nemasu
nemasu

Reputation: 426

sizeof (unsigned long)

Hmm, just from a quick glance this could be an issue, it will be 8 on 64bit machines, and 4 on 32bit machines.

Upvotes: 2

Related Questions