hashfile.c 833 Bytes
Newer Older
Julian Rother's avatar
Julian Rother committed
1
2
3
4
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
5
#include <libavutil/md5.h>
Julian Rother's avatar
Julian Rother committed
6
7
8
9
10

#include "../util.h"

char *hashfile(char *path)
{
11
	struct AVMD5 *ctx;
Julian Rother's avatar
Julian Rother committed
12
13
14
15
16
17
	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));
18
	if (!(ctx = av_md5_alloc()))
Julian Rother's avatar
Julian Rother committed
19
		exit(99);
20
	av_md5_init(ctx);
Julian Rother's avatar
Julian Rother committed
21
22
	buf = xmalloc(4096);
	while ((len = read(fd, buf, 4096)) > 0)
23
		av_md5_update(ctx, buf, len);
Julian Rother's avatar
Julian Rother committed
24
25
26
	if (len < 0)
		job_failed("Could not read file for hashing: %s", strerror(errno));
	close(fd);
27
	av_md5_final(ctx, buf);
Julian Rother's avatar
Julian Rother committed
28
29
30
	av_free(ctx);
	if (!(stream = open_memstream(&ptr, &size)))
		exit(99);
31
32
	fprintf(stream, "md5:");
	for (i = 0; i < 16; i ++)
Julian Rother's avatar
Julian Rother committed
33
34
35
36
37
		fprintf(stream, "%02hhx", buf[i]);
	free(buf);
	fclose(stream);
	return ptr;
}