user1089679
user1089679

Reputation: 2368

How can I add 2 byte CRC at the end of File

I have one encrypted file named encrypt. Here I calculated crc 16 for this file and store this crc result in unsigned short this unsigned short size is 2 byte(16 bits). Now I want to append 2 byte of crc value at the end of this file and read these last 2 bytes from file and have to compare this crc so how can I achieve this thing?

I used this code

fseek(readFile, filesize, SEEK_SET);
fprintf(readFile,"%u",result);

Here filesize is my file original encrypted file size and after this i add result which is unsigned short but in file its write 5 bytes.

file content after this

testsgh
30549 

original file data is testsgh but here crc is 30459 I want to store this value in 2 byte. so how can I do?

Upvotes: 1

Views: 3104

Answers (4)

Jörg Beyer
Jörg Beyer

Reputation: 3671

you can write single characters with %c formating. e.g.

fprintf(readfile, "%c%c", result % 256, result / 256)

btw: readfile is misleading, when you write to it :-)

Upvotes: 0

MPortilheiro
MPortilheiro

Reputation: 128

You could do something like this:

unsigned char c1, c2;
c1 = (unsigned char)(result >> 8);
c2 = (unsigned char)( (result << 8) >> 8);

and then append c1 and c2 at the end of the file. When you read the file back, just do the opposite:

result = ( (unsigned)c1 << 8 ) + (unsigned)c2;

Hope that helps.

Upvotes: 0

svinja
svinja

Reputation: 5576

Use fwrite(), not fprintf. I don't have access to a C compiler atm but fwrite(&result, sizeof(result), 1, readFile); should work.

Upvotes: 0

unwind
unwind

Reputation: 399833

You should open the file in binary append mode:

FILE *out = fopen("myfile.bin", "ab");

This will eliminate the need to seek to the end.

Then, you need to use a direct write, not a print which converts the value to a string and writes the string. You want to write the bits of your unsigned short checksum:

const size_t wrote = fwrite(&checksum, sizeof checksum, 1, out);

This succeeded if and only if the value of wrote is 1.

However, please note that this risks introducing endianness errors, since it writes the value using your machine's local byte order. To be on the safe side, it's cleaner to decide on a byte ordering and implement it directly. For big-endian:

const unsigned char check_bytes[2] = { checksum >> 8, checksum & 255 };
const size_t wrote = fwrite(check_bytes, sizeof check_bytes, 1, out);

Again, we expect wrote to be 1 after the call to indicate that both bytes were successfully written.

Upvotes: 3

Related Questions