I have implemented a function to produce a 32-bit checksum of a file using the following method: checksum = word_1 + word_2 + ... + word_n
, where word_i
is the 32-bit words the file consists of.
Here are several questions I'm very interested about:
- Is the way I read file word by word correct or there is a better way? (I aim not to read the whole file at once because it can be very large.)
- Are there any problems with chosen data types such as uint32_t, unsigned and so on?
- Have I got the right way to handle a file that isn't N*4 bytes in size? For example, for 7 bytes file I'm just setting 0-8 bits into 0 to avoid using an accidental value. Or I should set 24-31 bits into 0?
Here is the code I have so far:
void execute(std::ifstream& file)
{
const size_t WORD_SIZE = sizeof(uint32_t);
file.seekg(0, ios::end);
auto sizeInBytes = file.tellg();
file.seekg(0);
uint32_t checksum = 0U; // ???
if(auto sizeInEntireWords = sizeInBytes / WORD_SIZE)
{
for(int i = 0; i < sizeInEntireWords; i++)
{
uint32_t word;
file.read(reinterpret_cast<char*>(&word), WORD_SIZE); // ???
checksum += word;
}
}
if(auto additionalSizeInBytes = sizeInBytes % WORD_SIZE)
{
uint32_t word;
file.read(reinterpret_cast<char*>(&word), WORD_SIZE);
word &= (~0U << (WORD_SIZE - additionalSizeInBytes * 8)); // ???
checksum += word;
}
cout << checksum << endl;
}
if
is not a bug inif(auto sizeInEntireWords = sizeInBytes / WORD_SIZE)
? \$\endgroup\$false
right? \$\endgroup\$if(size_t i = container.size()) { cout << "We're here if container is NOT empty and can use i that is != 0"; } else { cout << "We're here if container is empty and can use i that is == 0"; } // but i is not available here
\$\endgroup\$