aboutsummaryrefslogtreecommitdiff
path: root/core/read.c
blob: 82b74be38a2cea5ee3e6dd4278c8294b2852ab31 (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
92
93
94
95
96
#include "../lib/io/io.h"
#include "../lib/arg/arg.h"
#include "../lib/list/list.h"

#define BUF_SIZE 1024

void mode_all(int fd);
void mode_singleline(int fd);

enum Modes {
	MODE_ALL,
	MODE_SINGLELINE,
	MODE_SIZE
} mode;

char buf[BUF_SIZE] = "";
list_t *files;
void(*mode_funcs[MODE_SIZE])(int fd) = {
	mode_all,
	mode_singleline
};

void add_file(const char *path)
{
	list_append(files, (void*)path);
}


void add_stdin()
{
	list_append(files, 0);
}


void set_singleline_mode()
{
	mode = MODE_SINGLELINE;
}


void mode_all(int fd)
{
	u64 rs;
	while ((rs = read(fd, buf, BUF_SIZE - 1))) {
		buf[rs] = 0;
		wstd(buf);
	}
}


void mode_singleline(int fd)
{
	u64 rs;
	u64 has_newline_char = 0;
	char *p;
	while (!has_newline_char) {
		rs = read(fd, buf, BUF_SIZE - 1);
		for (p = buf; p < buf + rs; ++p) {
			if (*p == '\n') {
				has_newline_char = 1;
				*(p + 1) = 0;
				break;
			}
		}
		wstd(buf);
	}
}


int main(int argc, const char **argv)
{
	list_node_t *file;
	int fd;

	files = new_list();

	arg_register_default(&add_file);
	arg_register_flag("-", &add_stdin);
	arg_register_flag("-l", &set_singleline_mode);
	arg_parse_arg(argc, argv);

	if (files->size == 0) {
		list_append(files, 0);
	}

	for (file = files->first; file; file = file->next) {
		if (file->value)
			fd = open(file->value, OPEN_READ_ONLY, 0);
		else
			fd = STDIN_FD;

		mode_funcs[mode](fd);
	}

	free_list(files);
}