I have a program which calculates md5 hash. I can enter the text and it will generate the md5 code. I want to get files from computer, for example text file and generate md5 for that. The problem is that i don't know how to get the file location and assign it to variable so i can put that variable in md5 generator function.
cout << "md5 of 'grape': " << md5("example") << endl;
as you can see in the above code i enter the md5 function argument which is "example" string, so i want something like this
string foo = "C:\\Users\\User\\Downloads\\1.txt";
cout << "md5 of 'grape': " << md5(foo) << endl;
so this will calculate md5 for "C:\\Users\\User\\Downloads\\1.txt" string, but i want to calculate the 1.txt file's md5.
One way to do it is by reading the whole file into a string and passing it to md5 function like this (I assume you are using zedwood's md5 ):
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include "md5.h"
int main()
{
MD5 md5;
std::ifstream ifs("C:\\Users\\User\\Downloads\\1.txt", std::ios::binary);
if (ifs)
{
std::ostringstream oss;
oss << ifs.rdbuf();
std::string s(oss.str());
md5.update(s.data(), s.size());
md5.finalize();
std::cout << md5.hexdigest() << std::endl;
}
return 0;
}
This should work with non-text files too.
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.