stdin example

This example shows how to use to calculate the CRC from a file, in this case stdin. This code was supplied by setop and slightly modified by the author of pycrc. The main function is:

#include <stdio.h>
#include "crc.h"

#define BLOCK_SIZE 4096

int main(void)
    char buffer[BLOCK_SIZE];
    crc_t crc = crc_init();
    while (!feof(stdin)) {
        size_t bytes = fread(buffer, BLOCK_SIZE, 1, stdin);
        crc = crc_update(crc, buffer, bytes);
    crc = crc_finalize(crc);
    printf("%lx\n", (unsigned long)crc);
    return 0;

Generate the header file (crc.h) and the CRC implementation (crc.c) with the usual commands (e.g. for crc-16):

python --model crc-16 --algorithm table-driven --generate h -o crc.h
python --model crc-16 --algorithm table-driven --generate c -o crc.c

Compile the *.c files and run the program.

gcc -W -Wall -std=c99 crc.c main.c -o crc

This will read the data from stdin and will print the resulting CRC once the end of file is reached. To insert an end-of-file on the keyboard press CTRL-D.

Alternatively redirect the input from a file or use a pipe to calculate the CRC of the output of a program:

./crc < /path/to/file
program | ./crc