summaryrefslogtreecommitdiff
path: root/main.cpp
blob: 047b5565ba1e5e3f4a1b01ef9e128bd62f0b23df (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
#include <iostream>
#include <ctime>
#include <sys/time.h>


static void print_usage(const char *argv0) {
	std::cerr
		<< "Usage: " << argv0 << " [OPTIONS]\n"
		<< "  -h    Show this help\n"
		<< "  -t    Print tags in local time format\n"
		<< "  -s    Print tags in timestamp format\n"
		<< std::flush;
}

int main(int argc, char **argv) {
	bool print_local_time = true;
	for (int i = 1; i < argc; i++) {
		if (argv[i][0] != '-') {
			std::cerr << "Unrecognised argument: '" << argv[i] << "'" << std::endl;
			print_usage(argv[0]);
			return 1;
		}
		for (int j = 1; argv[i][j]; j++) {
			switch (argv[i][j]) {
				case 'h': print_usage(argv[0]); return 0;
				case 't': print_local_time = true; break;
				case 's': print_local_time = false; break;
			}
		}
	}

	std::string line;
	while (std::getline(std::cin, line)) {
		struct timeval tv;
		gettimeofday(&tv, nullptr);

		char buffer[128];
		ssize_t nw = 0;
		if (print_local_time) {
			const struct tm *tm = localtime(&tv.tv_sec);
			nw = strftime(buffer, sizeof buffer - 7, "%Y-%m-%d %H:%M:%S.", tm);
		} else {
			nw = snprintf(buffer, sizeof buffer - 7, "%ld.", tv.tv_sec);
		}

		int multiplier = 100000;
		for (int i = 0; i < 6; i++) {
			buffer[nw + i] = '0' + tv.tv_usec / multiplier % 10;
			multiplier /= 10;
		}
		buffer[nw + 6] = '\0';

		std::cout << buffer << ' ' << line << std::endl;
	}
}