散列函数在删除和替换文件后返回不同的结果

时间:2019-04-10 14:52:59

标签: c loops while-loop openssl sha

我的问题是,当我运行程序并删除所述目录中的文件时,当该文件(相同文件)放回原位时,它将返回不同的值。我想知道下面的代码是否有问题?

int main (int argc, char *argv[])
{
        int fd;
        int wd;
        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[500];
        char hashOutBuf[500];
        fd = inotify_init();

        if (fd < 0) {
          perror("inotify_init");
        }

        wd = inotify_add_watch(fd, "/home/joe/Documents", IN_CREATE);

        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)) {
                    snprintf(hashInBuf, sizeof(hashInBuf), "%s/%s", directory, event->name);
                    snprintf(hashOutBuf, sizeof(hashOutBuf), "%s/%s.txt", hashDirectory, event->name);
                    //OPEN FILES
                    FILE *ftest=fopen(hashInBuf, "rb");    //ORIGINAL FILE
                    FILE *ftest2=fopen(hashOutBuf, "wt");  //HASH FILE (stored in separate directory)
                    //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;
         } //CLOSES INT MAIN

我可以向您保证变量定义正确,因为它可以正常工作,只是不正确...

1 个答案:

答案 0 :(得分:1)

您永远不会设置 hashInBuf hashOutBuf ,所以其中的内容是未定义的,并且在您执行时

zsh

您尝试打开从未设置名称的文件,但是很遗憾,您没有检查打开失败的位置,所以

               FILE *ftest=fopen(hashInBuf, "rb");    //ORIGINAL FILE
               FILE *ftest2=fopen(hashOutBuf, "wt");  //HASH FILE (stored in separate directory)

不读取任何内容,并且由于 ftest 的值为NULL,因此从未调用while ((bytes = fread (data, 1, 1024, ftest)) != 0)

从不使用几个变量:

  • file512
  • hashDirectory
  • 目录
  • wd
  • argc
  • argv