简体   繁体   中英

How can i modify this program so it calculates the hash without modifying the file?

i have after alot of troubles finally come up with this code. It calculates the hash of a text file, and adds the hash to the file. Obviously, that changes the hash, so when i run it again i will get another hash.

However, if i just want to get the hash in its current state without changing it - what should i be changing in my code? Is it the "f = fopen (apszArgV[1], "rb+");" who causes the hash to change?

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

#define BUFFER_SIZE 1024

void print_hash(char hash[]);

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: md5_add <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);

      f = fopen("fil1.txt", "a");

      for (int i = 0; i < 15; i++) {
          fprintf (f, "%02X", byHash[i]);
      }
      fprintf(f, "\n");
      fclose (f);
   }

   print_hash(byHash);

}

void print_hash(char hash[]) 
{
   int idx; 
   for (idx=0; idx < 16; idx++) 
      printf("%02x",(int)((unsigned char)hash[idx])); 
   printf("\n"); 
}  

thanks

new to c btw

Sorry, cannot comment by now. In difference to the question before you actually already open 2 different files. To be honest i dont see in your code why it should still print to the same file that you first read for hashing but i see you need to clean up.

1) name pointers in a way you can see what they actually do:

Instead of

   FILE *f;

name it

File * file_to_be_hashed;

Then better declare a new name for your output file.

FILE * listOfHashes = fopen("fil1.txt", "a");

Also do not forget to close the files when you are done with them:

md5_final(&ctx, byHash)
fclose(f);

But as said, i dont really see why your code would still print into your input file, except maybe fopen to "fil2.txt" dont work. My guess is the file fil2.txt does not yet exist so it cannot be opened for appending as you specify in fopen("fil1.txt", "a");

Also there is no reason for the first fopen to be rb+ as r provides enough rights for reading ;-)

Maybe you learn about what the open flags of fopen actually mean... http://pubs.opengroup.org/onlinepubs/009695399/functions/fopen.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM