The C program below that calculates the checksum for the text in a file.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
// Function to calculate checksum based on the specified size
uint32_t calculateChecksum(FILE *file, int checksumSize) {
uint32_t checksum = 0;
while (!feof(file))
char ch = fgetc(file);
checksum = (checksum << 8)
// Truncate the checksum based on the specified size
checksum = checksum & ((1 << checksumSize) - 1);
return checksum;
}
int main(int argc, char *argv[]) {
// Check the number of command line arguments
if (argc != 3) {
fprintf(stderr, "Usage: %s <input_file> <checksum_size>\\", argv[0]);
return EXIT_FAILURE;
}
// Parse the checksum size
int checksumSize = atoi(argv[2]);
// Check if the checksum size is valid
if (checksumSize != 8 && checksumSize != 16 && checksumSize != 32) {
fprintf(stderr, "Valid checksum sizes are 8, 16, or 32.\\");
return EXIT_FAILURE;
}
// Open the input file
FILE *inputFile = fopen(argv[1], "rb");
if (inputFile == NULL) {
perror("Error opening input file");
return EXIT_FAILURE;
}
// Display the processed input
printf("Processed Input:\\");
fseek(inputFile, 0, SEEK_SET);
int ch;
while ((ch = fgetc(inputFile)) != EOF) {
putchar(ch);
}
printf("\\");
// Calculate and display the checksum
uint32_t checksum = calculateChecksum(inputFile, checksumSize);
printf("Checksum (%d bits): %u\\", checksumSize, checksum);
// Close the input file
fclose(inputFile);
return EXIT_SUCCESS;
}
To Compile the program using a C compiler (e.g., gcc): gcc -o checksum checksum.c
So, to run the program using the sample command: ./checksum input.txt 8