summaryrefslogtreecommitdiff
path: root/statefile.c
blob: 08fb3721a3192decabb3fe7ce0ac02c91e160dff (plain)
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <stdio.h>
#include <errno.h>
#include <stdint.h>
#include <string.h>

#include "config.h"

int
state_load(config_t* conf, uint32_t* map, uint32_t* jobs_done) {
	FILE*  fh = NULL;
	size_t mapsize;
	int    errsv;

	mapsize = conf->width * conf->height * conf->iters_n;

	if(!(fh = fopen(conf->statefile, "rb"))) {
		if(errno == ENOENT) {
			memset(map, 0, mapsize);
			*jobs_done = 0;
			return 1;
		}

		return 0;
	}

	if(fread(jobs_done, sizeof(uint32_t), 1, fh) != 1) {
		errsv = errno;
		fclose(fh);
		errno = errsv;
		return 0;
	}

	if(fread(map, sizeof(uint32_t), mapsize, fh) != mapsize) {
		errsv = errno;
		fclose(fh);
		errno = errsv;
		return 0;
	}

	fclose(fh);
	return 1;
}

int
state_save(config_t* conf, uint32_t* map, uint32_t jobs_done) {
	FILE*  fh = NULL;
	size_t mapsize;
	int    errsv;

	mapsize = conf->width * conf->height * conf->iters_n;

	if(!(fh = fopen(conf->statefile, "wb"))) {
		return 0;
	}

	if(fwrite(&jobs_done, sizeof(uint32_t), 1, fh) != 1) {
		errsv = errno;
		fclose(fh);
		errno = errsv;
		return 0;
	}

	if(fwrite(map, sizeof(uint32_t), mapsize, fh) != mapsize) {
		errsv = errno;
		fclose(fh);
		errno = errsv;
		return 0;
	}

	fclose(fh);
	return 1;
}