hashfile.c 833 Bytes
Newer Older
Julian Rother's avatar
Julian Rother committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <libavutil/md5.h>

#include "../util.h"

char *hashfile(char *path)
{
	struct AVMD5 *ctx;
	int i, fd;
	char *ptr, *buf;
	size_t len, size;
	FILE *stream;
	if ((fd = open(path, O_RDONLY)) < 0)
		job_failed("Could not open file for hashing: %s", strerror(errno));
	if (!(ctx = av_md5_alloc()))
		exit(99);
	av_md5_init(ctx);
	buf = xmalloc(4096);
	while ((len = read(fd, buf, 4096)) > 0)
		av_md5_update(ctx, buf, len);
	if (len < 0)
		job_failed("Could not read file for hashing: %s", strerror(errno));
	close(fd);
	av_md5_final(ctx, buf);
	av_free(ctx);
	if (!(stream = open_memstream(&ptr, &size)))
		exit(99);
	fprintf(stream, "md5:");
	for (i = 0; i < 16; i ++)
		fprintf(stream, "%02hhx", buf[i]);
	free(buf);
	fclose(stream);
	return ptr;
}