md5sum of file in Linux C md5sum of file in Linux C linux linux

md5sum of file in Linux C


There's code here.

Also, the openssl libs have md5 functions (from here):

#include <openssl/md5.h>#include <unistd.h>int main(){    int n;    MD5_CTX c;    char buf[512];    ssize_t bytes;    unsigned char out[MD5_DIGEST_LENGTH];    MD5_Init(&c);    bytes=read(STDIN_FILENO, buf, 512);    while(bytes > 0)    {        MD5_Update(&c, buf, bytes);        bytes=read(STDIN_FILENO, buf, 512);    }    MD5_Final(out, &c);    for(n=0; n<MD5_DIGEST_LENGTH; n++)        printf("%02x", out[n]);    printf("\n");    return(0);        }


You can use popen to run md5sum and read the output:

#include <stdio.h>#include <ctype.h>#define STR_VALUE(val) #val#define STR(name) STR_VALUE(name)#define PATH_LEN 256#define MD5_LEN 32int CalcFileMD5(char *file_name, char *md5_sum){    #define MD5SUM_CMD_FMT "md5sum %." STR(PATH_LEN) "s 2>/dev/null"    char cmd[PATH_LEN + sizeof (MD5SUM_CMD_FMT)];    sprintf(cmd, MD5SUM_CMD_FMT, file_name);    #undef MD5SUM_CMD_FMT    FILE *p = popen(cmd, "r");    if (p == NULL) return 0;    int i, ch;    for (i = 0; i < MD5_LEN && isxdigit(ch = fgetc(p)); i++) {        *md5_sum++ = ch;    }    *md5_sum = '\0';    pclose(p);    return i == MD5_LEN;}int main(int argc, char *argv[]){    char md5[MD5_LEN + 1];    if (!CalcFileMD5("~/testfile", md5)) {        puts("Error occured!");    } else {        printf("Success! MD5 sum is: %s\n", md5);    }}


You can use the mhash library (license is LGPL). On Debian systems:

sudo apt-get install libmhash-dev

See the man page man 3 mhash

But I don't think you can just give it the name of a file. You have to open the file yourself, read the data, and feed the data to this library's functions.