CRC32 Self-checking file

If the CRC of a file is appended properly to that file, then the composite can be verified by computing the CRC on it. If it has not been corrupted, it will yield the known constant. In the case of the commonly used CRC32, that constant is 32 ones or 0xffffffff. Here is an example of how to do this after you have set the file path. The file must be writable and not open for writing when this is run.

package require crc32

set c32 [crc::crc32 -filename $file]    ;# its original 32 bit crc
puts "$file has [file size $file] bytes; hex CRC32 is [format "%08x" $c32]"

set c32i [expr $c32 ^ 0xffffffff]       ;# ones complement
for {set i 0} {$i<=3} {incr i} {
    lappend bytes_i [expr $c32i & 0xff] ;# list of inverted bytes
    set c32i [expr $c32i >> 8]          ;# ready for next byte
}

set bytes [binary format c4 $bytes_i]   ;# convert to string of 8-bit integers

set ofid [open "$file" "a"]
fconfigure $ofid -translation binary
puts -nonewline $ofid $bytes            ;# append four bytes
close $ofid

set c32 [crc::crc32 -filename $file]    ;# its self-checking 32 bit crc
puts "$file has [file size $file] bytes; hex CRC32 is [format "%08x" $c32]"