因为我使用tftp命令传输一个重要文件,所以我想比较md5以使传输生效。注意:文件已经在下面的示例中传输
int main(int argc, char *argv[])
{
FILE *input_md5_fd;
FILE *md5_fd;
size_t md5_length;
size_t nbr_items;
char *input_md5 = NULL;
char *file_md5 = NULL;
int ret;
chdir("/tmp");
system("tftp -g -r INPUT_MD5 192.168.0.1");
input_md5_fd = fopen("INPUT_MD5", "r");
if (input_md5_fd != NULL)
{
fprintf(stdout,"MD5 transfered\n");
fseek(input_md5_fd,0L,SEEK_END);
md5_length = ftell(md5_fd);
input_md5 = malloc(md5_length + 1);
fseek(input_md5_fd,0L,SEEK_SET);
nbr_items = fread(input_md5, 1, md5_length, input_md5_fd);
input_md5[nbr_items] = 0;
fprintf(stdout, "length = %lu B\n",md5_length);
fprintf(stdout, "contains %s\n", input_md5);
fclose(input_md5_fd);
}
else
{
return -1;
}
system("md5sum IMPORTANT_FILE > /tmp/file_md5.txt");
md5_fd = fopen("file_md5.txt", "r");
if (md5_fd != NULL)
{
file_md5 = malloc(md5_length +1);
rewind(md5_fd);
nbr_items = fread(file_md5, 1, md5_length, md5_fd);
file_md5[nbr_items] = 0;
fprintf(stdout, "contains %s\n", file_md5);
fclose(md5_fd);
}
else
{
return -1;
}
printf("file_md5 = %s\n", file_md5);
printf("input_md5 = %s\n", input_md5);
ret = strncmp(file_md5, input_md5, md5_length);
printf("ret = %d\n", ret);
free(input_md5);
free(file_md5);
}
输出 :
MD5 transfered
length = 33 B
contains a95ef51ec6b1b06f61c97559ddf4868f
contains a95ef51ec6b1b06f61c97559ddf4868f
file_md5 = a95ef51ec6b1b06f61c97559ddf4868f
input_md5 = a95ef51ec6b1b06f61c97559ddf4868f
ret = 22
输入文件包含:
# cat /tmp/INPUT_MD5
a95ef51ec6b1b06f61c97559ddf4868f
# cat /tmp/file_md5
a95ef51ec6b1b06f61c97559ddf4868f XXX_XX-XXXX-XX-DD.DDD-DD.DDD.DD.bin
X 是 char 和 D 十进制值。
为什么 ret 不等于 0 ?另外,不知道34是从哪里来的
编辑:代码已更新,问题来自 md5_length 定义。long 类型已换成 size_t