elleryq
7/8/2014 - 6:48 AM

For each 512 bytes in the input binary file, calculate the 16-bit checksum and write the 512 bytes with the checksum as the 512th byte to th

For each 512 bytes in the input binary file, calculate the 16-bit checksum and write the 512 bytes with the checksum as the 512th byte to the output binary file. At the end of the file, pad bytes might need to be added if the remaining byes in the input binary file is less then 512 bytes. If present, each pad byte shall be set to 0xff.

#include <stdio.h>
#include <stdlib.h>


#define BUFFER_SIZE 512

int doPadding(char* buffer, int startOffset) {
    int i;
    for(i = startOffset; i<BUFFER_SIZE; ++i) {
        *(buffer+i) = 0xff;
    }
    return 0;
}

char calcCheckSum(char* buffer, int size) {
    int i;
    char sum;
    for(i=0; i<size; i++) {
        sum += *(buffer+i);
    }
    return sum;
}

int main(int argc, char* argv[]) {
    FILE* fin = NULL, *fout = NULL;
    char buffer[BUFFER_SIZE];
    char checksum;
    size_t readed;
    if(argc < 3) {
        printf("need argument.\n");
        exit(-1);
    }

    fin = fopen(argv[1], "rb");
    if(!fin) {
        printf("Input file is not existed.\n");
        exit(-1);
    }
    fout = fopen(argv[2], "wb");
    while((readed=fread(buffer, sizeof(char), BUFFER_SIZE, fin))) {
        printf("readed=%ld\n", readed);
        checksum = calcCheckSum(buffer, readed);
        if(readed<BUFFER_SIZE) {
            doPadding(buffer, readed);
        }
        fwrite(buffer, sizeof(char), BUFFER_SIZE, fout);
        fwrite(&checksum, 1, sizeof(char), fout);
    }
    fclose(fin);
    fclose(fout);
}