I have been asked to create a checksum algorithm for a file transfer, the C++ code I have been given is as follows:
// ChecksumTestTool.cpp : Defines the entry point for the console
application.
//
#include "stdafx.h"
#include <string>
#include <stdio.h>
#include <iostream>
unsigned long CalculateChecksum(FILE* pFile);
int main(int argc, char *argv[])
{
int result = 0;
//Get filename from command args
std::string fileName;
if (argc >= 1)
{
fileName = argv[0];
//Open file with read access
FILE* pFile = nullptr;
int error = fopen_s(&pFile, fileName.c_str(), "r");
if (error != 0 || pFile == nullptr)
{
printf("Failed to open file with error %d\r\n", error);
result = -1;
}
else
{
//Calculate the checksum
unsigned long checksum = CalculateChecksum(pFile);
printf("Calculated Checksum for %s is %lu (0x%04X)\r\n",
fileName.c_str(), checksum, checksum);
}
}
else
{
printf("Must enter filename on command line\r\n");
result = -1;
}
//Wait here so we can see result
printf("\r\nPress Any Key to Exit\r\n");
getchar();
return 0;
}
unsigned long CalculateChecksum(FILE* pFile)
{
unsigned long checksum = 0;
//TODO:: Calculate the checksum
return checksum;
}
I need to create the checksum at the point '//TODO:: Calculate the checksum'. The algorithm need to check whether the file transfers or not. So far I have tried:
unsigned long CalculateChecksum(FILE* pFile)
{
unsigned long checksum = 0;
//TODO:: Calculate the checksum
unsigned long word = 0;
while (file.read(reinterpret_cast<char*>(&word), sizeof(word))); {
checksum += word;
}
if (file.gcount()); {
word &= (~0U >> ((sizeof(unsigned long) - file.gcount()) * 8));
checksum += word;
}
return checksum;
}
and I get errors saying 'file' is an undeclared identifier and that left '.gcount' must have class/struct/union
I have searched around for multiple checksums and this algorithm is the only one I found that works within this code