gpt4 book ai didi

c - 哈希程序不为同一文件返回相同的值

转载 作者:太空宇宙 更新时间:2023-11-04 03:11:46 26 4
gpt4 key购买 nike

我创建的这个散列函数(扫描新文件并计算它们的散列值)看似有效,但是一旦删除文件,例如 test.c,然后用完全相同的文件替换它,它会返回 2 个不同的哈希值。我的意思是,当程序运行时,第一个计算可能会返回 1234 的哈希值,例如,一旦删除相同的文件并将其放入文件夹中,它就会返回 2345。

似乎没有顺序,因为1234可能是连续5次的结果。我想知道这段代码中是否有任何非常明显的原因?

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <sys/inotify.h>
#include <openssl/sha.h>

int main (int argc, char *argv[])
{
int fd;
unsigned char c[SHA512_DIGEST_LENGTH];
int i;
SHA512_CTX mdContext;
int bytes;
unsigned char data[1024];
const int event_size = sizeof(struct inotify_event);
const int buf_len = 1024 * (event_size + FILENAME_MAX);
char *directory = "/home/joe/Documents/";
char *hashDirectory = "/home/joe/Documents/_Hash/";
char hashInBuf[100];
char hashOutBuf[100];
fd = inotify_init();

if (fd < 0) {
perror("inotify_init");
}
while (1) {
char buff[buf_len];
int no_of_events, count = 0;

//SEARCH FOR NEW FILES WITHIN DIRECTORY
no_of_events = read (fd, buff, buf_len);
while (count < no_of_events) {
struct inotify_event *event = (struct inotify_event *)&buff[count];
if (event->len) {
if ((event->mask & IN_CREATE))
if(!(event->mask & IN_ISDIR)) {
printf("\n%s has been created\n", event->name);

//CONJOIN DIRECTORY AND FILENAME / EXTENSION
snprintf(hashInBuf, sizeof(hashInBuf), "%s/%s", directory, event->name);
snprintf(hashOutBuf, sizeof(hashOutBuf), "%s/%s.txt", hashDirectory, event->name);

FILE *ftest=fopen(hashInBuf, "rb");
FILE *ftest2=fopen(hashOutBuf, "wt");

//HASH FUNCTION
SHA512_Init (&mdContext);
while ((bytes = fread (data, 1, 1024, ftest)) != 0)
SHA512_Update (&mdContext, data, bytes);
SHA512_Final (c,&mdContext);
for(i = 0; i < SHA512_DIGEST_LENGTH; i++){
fprintf(ftest2, "%02x", c[i]);
printf("%02x", c[i]);
}
fclose (ftest);
fclose (ftest2);
fflush (stdout);
}
}
count += event_size + event->len;
}
}
return 0;
}

提前致谢!

最佳答案

在这一行

if ((event->mask & IN_CREATE))

您等待文件创建 的事件。然后,您的哈希函数立即开始运行!这可能会导致文件完全写入的情况,因此您只散列了文件的部分

您应该使用事件 IN_CLOSE_WRITE 来确保文件已经完全写入。

另一种选择是在此目录中创建文件,而是在临时目录中创建它们,然后将它们移动到目标目录中。相应的事件是 IN_MOVED_TO 然后。

关于c - 哈希程序不为同一文件返回相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55653055/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com