summaryrefslogtreecommitdiffstats
path: root/src/io.c
blob: 74ea2746b36c2ac5b14baa3c0d16d8dd2d3854f0 (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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libgen.h>
#include "io.h"

int openstream(struct stream *in)
{
	struct stat st;
	mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP;
	char *dname = NULL;
	int ret = 0;

	in->fd = -1;

	if (!in->name) {
		ret = EINVAL;
		goto err;
	}

	if (in->out) {
		char *tmp[2];

		tmp[0] = strdup(in->name);
		tmp[1] = dirname(tmp[0]);
		dname = strdup(tmp[1]);
		free(tmp[0]);

		if (stat(dname, &st)) {
			ret = errno;
			/* TODO: error message */
			goto err;
		}

		if(!(st.st_mode & S_IFDIR)) {
			ret = EINVAL;
			/* TODO: error message */
			goto err;
		}

		if (!stat(in->name, &st)) {
			if (!(st.st_mode & S_IFREG)) {
				ret = EINVAL;
				/* TODO: error message */
				goto err;
			}
			mode = st.st_mode;
		}
	} else if (stat(in->name, &st)) {
		ret = errno;
		/* TODO: error message */
		goto err;
	} else if (!(st.st_mode & S_IFREG) || !st.st_size || (st.st_size % in->stride)) {
		ret = EINVAL;
		/* TODO: error message */
		goto err;
	} else {
		in->n = st.st_size / in->stride;
	}

	if (in->out) {
		in->fd = open(dname, O_TMPFILE | O_WRONLY, mode);
		if (in->fd < 0) {
			ret = errno;
			/* TODO: error message */
			goto err;
		}

		if (ftruncate(in->fd, in->stride * in->n)) {
			ret = errno;
			/* TODO: error message */
			goto err;
		}
	} else {
		in->fd = open(in->name, O_RDONLY | O_NOATIME);
		if (in->fd < 0) {
			ret = errno;
			/* TODO: error message */
			goto err;
		}
	}

err:
	free(dname);
	return ret;
}