0

I have spent the last 8 hours writing this:

#include <stdio.h>
#include "md5.h"

#define BUFFER_SIZE 1024

void PrintHash (BYTE byHash[]);

int main (int iArgC, char *apszArgV[])
{
   FILE *f;
   MD5_CTX ctx;          
   BYTE byHash[16];            
   BYTE byBuffer[BUFFER_SIZE]; 
   int iReadBytes;             

   if (iArgC < 2) {
      printf ("Usage: print_md5 <file name>\n");
      return 1;
   }

   f = fopen (apszArgV[1], "rb+");
   if (f != NULL) {

      md5_init(&ctx);   

      while (!feof(f)) {
         iReadBytes = fread(byBuffer, sizeof(BYTE), BUFFER_SIZE, f);
         md5_update(&ctx, byBuffer, iReadBytes);  
         if (iReadBytes < BUFFER_SIZE) break;
      }

      md5_final(&ctx, byHash);


      printf("File:%s Md5:", apszArgV[1]);
      PrintHash (byHash);
      printf ("\n");

      fclose (f);
   }
}

void PrintHash (BYTE byHash[])
{
   for (int i = 0; i < 15; i++) {
      printf ("%02X", byHash[i]);
   }
}

Now all i want to do, is to write the hash to the last line of the same file i have calculated the hash from.

I have tried putting this at the same line where i call the PrintHash function, does not seem to work as it generates a new hash for the same file every time i run it.

f = fopen(apszArgV[1],"a");

         for(i=0; i<16 ;i++) {
            fprintf(fp, "%02X", byHash[i]);

         }
         fclose(fp);

May someone point out what i am doing wrong?

new to c btw

  • 2
    If you are appending to the file you are hashing, the hash will be different each time you run, because the contents of the file will be different. You should notice that the file gets larger by 16 bytes each time you run, and different file sizes result in a different hash. – cxw Oct 10 '17 at 15:53
  • 1
    [Why is “while ( !feof (file) )” always wrong?](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – Eugene Sh. Oct 10 '17 at 15:53
  • 1
    Do you mean `fp = fopen....` ? – Ajay Brahmakshatriya Oct 10 '17 at 16:00

0 Answers0