📄 genchecksum.c
字号:
/* * Calculate the checksum and put it into the same file (the last * 4 bytes. */#include <stdio.h>#include <sys/types.h>#include <sys/stat.h>#include <unistd.h>#include <fcntl.h> static int fno = 0;static struct stat statbuf;int main(int argc, char *argv[]){ unsigned long val, sum = 0; off_t offset = 0; unsigned new_size = 0; if (argc != 2) { fprintf(stderr, "usage: %s file_name\n", argv[0]); return(-1); } else if (stat(argv[1], &statbuf) < 0) { fprintf(stderr, "error open %s\n", argv[1]); return(-1); } else if ((statbuf.st_size & 0xffff) != 0) { fprintf(stderr, "file %s is not 64KB aligned\n", argv[1]); return(-1); } else if (statbuf.st_size == 0) { fprintf(stderr, "file %s size is 0 byte\n", argv[1]); return(-1); } else if ((fno = open(argv[1], O_RDWR)) <= 0) { fprintf(stderr, "error open %s\n", argv[1]); return(-1); } while (read(fno, &val, sizeof(unsigned long)) == sizeof(unsigned long)) { sum += val; } fprintf(stdout, "Sum is 0x%lx, ", sum); sum = ~sum + 1; fprintf(stdout, "checksum is 0x%lx, ", sum); if (val != 0) { offset = 0; fprintf(stdout, "Warning: appending checksum.\n"); } else { offset = -1 * sizeof(unsigned long); fprintf(stdout, "inserting checksum.\n"); } if (lseek(fno, offset, SEEK_END) < 0) { fprintf(stderr, "error seeking from the end of %s\n", argv[1]); close(fno); return(-1); } if (write(fno, &sum, sizeof(unsigned long)) != sizeof(unsigned long)) { fprintf(stderr, "error writing checksum to %s\n", argv[1]); close(fno); return(-1); } new_size = ((val == 0) ? statbuf.st_size : statbuf.st_size + sizeof(unsigned long)); fprintf(stdout, "Final file size (%s) is %d.\n", argv[1], new_size); if ((new_size & 0xffff) != 0) fprintf(stdout, "WARNING: %s not aligned in 64KB boundary\n", argv[1]); close(fno);}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -