【发布时间】:2017-08-01 17:21:30
【问题描述】:
我的程序读取一个文件,通过将文件处理为 4 字节整数并对每个块求和来计算 4 字节校验和,然后将其与预先计算的校验和进行比较以检查文件的有效性。
例如,hello_world.txt 可能包含以下内容。
你好世界
我已经预先计算了校验和,我知道是0x49f247db,但是最后比较失败了。
这可能是什么问题?是我获取 4 字节整数的方式吗?
我试图通过将缓冲区的指针转换为整数指针并使用“++”运算符迭代缓冲区来完成此操作,但它最终会以某种方式跳过字节。
这是我正在使用的代码。
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
int main() {
unsigned char buffer [1024];
unsigned long int checksum = 0;
FILE *fp;
int i;
unsigned long int length;
fp = open ("hello_world.txt", 0, 0);
if (fp == NULL) exit(0);
for (;;)
{
memset (buffer, 0, sizeof(buffer));
/* Read the next chunk of the file */
length = read (fp, &buffer, 1024);
if (length == 0)
break;
printf("i'm here. %d %s \n", length, strerror(errno));
/* We've read a chunk of the file -- all chunks (except the last)
* will be '1024' bytes in length; the last chunk will
* probably be less than '1024' bytes.
*/
for (i=0; i<length; i+=4)
{
unsigned long int a = (unsigned long int) ((unsigned char)(buffer[i]) << 24 |
(unsigned char)(buffer[i+1]) << 16 |
(unsigned char)(buffer[i+2]) << 8 |
(unsigned char)(buffer[i+3]));
checksum += a;
}
}
printf("%d, %x \n", checksum, checksum);
if (0x49f247db == checksum) printf("CHECKSUM MATCHED");
/* Close the file and return the checksum */
close (fp);
return 0;
}
【问题讨论】:
-
魔法会发生。不,实际上它不能。你的代码在哪里?
-
a=10; b = 16; printf("%u %x\n", a,b);- 至少它们的打印相同。 -
这可能是因为这两个数字实际上不同。可能是因为您使用不正确的技术(可能是
%d)打印它们,无意中使它们看起来相同。这可能是因为在您打印它们并比较它们之间发生了一些变化。你为什么不给我们看你的代码,这样我们就不用胡乱猜测了? -
原帖已更新