]> git.scottworley.com Git - tl-append/blame - tl-append.c
Interactive mode: Prompt, feedback, & screen clearing
[tl-append] / tl-append.c
CommitLineData
e81b7a5f
SW
1#define _POSIX_C_SOURCE 199309L
2
3#include <errno.h>
b3d5ed96
SW
4#include <stdio.h>
5#include <stdlib.h>
e81b7a5f
SW
6#include <string.h>
7#include <time.h>
8#include <unistd.h>
b3d5ed96 9
d522116b 10#include "common.h"
b3d5ed96 11
d522116b 12const size_t BUF_SIZE = 1024;
b3d5ed96 13
e81b7a5f
SW
14const char PROMPT[] = "\33[H" /* Move cursor 'home' */
15 "\33[J" /* Clear screen */
16 "> ";
17const char ACKNOWLEDGE[] = "[OK]";
18const struct timespec ACKNOWLEDGE_DELAY = {0, 300000000};
19
20typedef struct {
21 int interactive;
22} conf_t;
23
24conf_t parse_command_line(int argc, char *argv[]) {
25 conf_t conf = {0};
26
27 if (argc == 2 && strcmp(argv[1], "-i") == 0 && isatty(2))
28 conf.interactive = 1;
29
30 return conf;
31}
32
33static void read_line(conf_t conf, char *buf) {
34 if (conf.interactive)
35 if (fputs(PROMPT, stderr) == EOF)
36 die("I/O error writing prompt");
b3d5ed96
SW
37 if (fgets(buf, BUF_SIZE, stdin) == NULL) {
38 if (ferror(stdin))
39 die("I/O error reading line");
40 if (feof(stdin)) {
41 buf[0] = '\0'; /* Unclear if fgets does this already */
42 return;
43 }
44 die("Unexpected error reading line");
45 }
46}
47
e81b7a5f 48static void write_line(conf_t conf, const char *line) {
2998af81 49 const char *now = encode_time(time(NULL));
b3d5ed96
SW
50 FILE *f = fopen(FILENAME, "a");
51 if (f == NULL)
52 die_err("Error opening output file");
2998af81
SW
53 if (fputs(now, f) == EOF)
54 die("Error writing to output file");
55 if (fputc(' ', f) == EOF)
56 die("Error writing to output file");
b3d5ed96
SW
57 if (fputs(line, f) == EOF)
58 die("Error writing to output file");
59 if (fclose(f) != 0)
60 die_err("Error closing output file");
e81b7a5f
SW
61 if (conf.interactive) {
62 if (fputs(ACKNOWLEDGE, stderr) == EOF)
63 die("Error writing acknowledgment");
64 if (nanosleep(&ACKNOWLEDGE_DELAY, NULL) == -1 && errno != EINTR)
65 die_err("Error sleeping");
66 }
b3d5ed96
SW
67}
68
e81b7a5f
SW
69int main(int argc, char *argv[]) {
70 conf_t conf = parse_command_line(argc, argv);
b3d5ed96 71 char buf[BUF_SIZE];
e81b7a5f
SW
72 for (read_line(conf, buf); buf[0]; read_line(conf, buf)) {
73 write_line(conf, buf);
b3d5ed96
SW
74 }
75 return 0;
76}