FastCRC Library API

The following sample demonstrates how to use the CRC16 API to calculate the CRC16 checksum for a file.

#include <stdio.h>
#include <FastCRC.h>

#define BUFF_SIZE  1024

int CalculateFileChecksum1( const char* filename, char* checksumhex )
{
    /*****Calculate checksum using CalculateFile*******************************/

    unsigned long checksum;

    /*****Get the checksum in hexadecimal representation***********************/

    if( SL_FCRC16_CalculateFile( &checksum, filename ) != 0 )
        return 0;

    SL_FCRC_ConvertToHex16( checksumhex, checksum, 0 );

    return 1;
}

int CalculateFileChecksum2( const char* filename, char* checksumhex )
{
    /*****Calculate checksum using Update and Final****************************/

    FILE* file;
    unsigned char buff[ BUFF_SIZE ];
    unsigned long checksum;
    unsigned long crcvar;

    file = fopen( filename, "rb" );

    if( file == NULL )
    {
        printf( "\nCould not open file: %s", filename );
        return 0;
    }

    /*****Initialize the crcvar before calling Update, Final*******************/

    SL_FCRC16_Init( &crcvar );

    /*****Calculate the checksum by calling Update for each block of the file**/

    while( !feof( file ) )
    {
        unsigned int nCount = fread( buff, sizeof( char ), BUFF_SIZE, file );
        if( ferror( file ) )
        {
            printf( "\nAn error occurred when accessing the file: %s", filename );
            fclose( file );
            return 0;
        }
        SL_FCRC16_Update( &crcvar, buff, nCount );
    }

    /*****Do final changes and get the checksum in hexadecimal representation***/

    checksum = SL_FCRC16_Final( &crcvar ); /* SL_FCRC16_Final reinitializes the crcvar */

    SL_FCRC_ConvertToHex16( checksumhex, checksum, 0 );

    fclose( file );

    return 1;
}

int main()
{
    char buff[ 256 ];
    char checksumhex[ SLC_FCRC_MAXHEXSIZE ]; /*0 terminated*/

    do
    {
        /*****Get the file name from the user*************************************/

        printf( "\nEnter a file name:\n" );
        gets( buff );

        /*****Calculate the checksum using CalculateFile**************************/

        if( CalculateFileChecksum1( buff, checksumhex ) != 0 )
            printf( "\nChecksum calculated using CalculateFile:    %s", checksumhex );

        /*****Calculate the checksum using Update and Final***********************/

        if( CalculateFileChecksum2( buff, checksumhex ) != 0 )
            printf( "\nChecksum calculated using Update and Final: %s", checksumhex );

        /*****Continue?***********************************************************/

        printf( "\nContinue (Y/N)?" );
        gets( buff );

    } while ( *buff == 'y' || *buff == 'Y' );

    return 0;
}

        

 


 

 

Send Feedback to SlavaSoft Inc. Tell a friend about FastCRC Library