aboutsummaryrefslogtreecommitdiff
path: root/addts.c
diff options
context:
space:
mode:
authorSergey Poznyakoff <gray@gnu.org>2018-06-20 12:06:26 +0300
committerSergey Poznyakoff <gray@gnu.org>2018-06-20 12:57:57 +0300
commitab01873f6f7e26fde46e6a7808742289d6be28d6 (patch)
tree02cb87130b520c24163877d8eadf5cfa5b9d78ef /addts.c
downloadaddts-ab01873f6f7e26fde46e6a7808742289d6be28d6.tar.gz
addts-ab01873f6f7e26fde46e6a7808742289d6be28d6.tar.bz2
Initial commit
Diffstat (limited to 'addts.c')
-rw-r--r--addts.c125
1 files changed, 125 insertions, 0 deletions
diff --git a/addts.c b/addts.c
new file mode 100644
index 0000000..abd3c9a
--- /dev/null
+++ b/addts.c
@@ -0,0 +1,125 @@
+#include <stdlib.h>
+#include <stdio.h>
+#include <unistd.h>
+#include <string.h>
+#include <errno.h>
+#include <time.h>
+#include <sys/time.h>
+
+static char default_fmt[] = "%Y-%m-%d %H:%M:%S: ";
+
+int
+main(int argc, char **argv)
+{
+ int c;
+ char buf[512];
+ int eol = 0;
+ int utc_opt = 0;
+ int append_opt = 0;
+ int ws_opt = 0;
+ unsigned long ignore = 0;
+ char *p;
+ char *fmt = NULL;
+ FILE *fp;
+
+ while ((c = getopt(argc, argv, "?af:i:uw:")) != EOF) {
+ switch (c) {
+ case 'a':
+ append_opt = 1;
+ break;
+ case 'f':
+ fmt = optarg;
+ break;
+ case 'i':
+ errno = 0;
+ ignore = strtoul(optarg, &p, 10);
+ if (errno || *p) {
+ fprintf(stderr,
+ "%s: -i argument is not a number\n",
+ argv[0]);
+ return 1;
+ }
+ break;
+ case 'u':
+ utc_opt = 1;
+ break;
+ case 'w':
+ ws_opt = optarg[0];
+ break;
+ default:
+ if (optopt == 0) {
+ printf("usage: %s [-a] [-f FMT] [-i N] [-u] [OUT-FILE]\n", argv[0]);
+ return 0;
+ }
+ return 1;
+ }
+ }
+
+ if (fmt) {
+ if (ws_opt) {
+ for (p = fmt; *p; p++)
+ if (*p == ws_opt)
+ *p = ' ';
+ }
+ } else
+ fmt = default_fmt;
+
+ argc -= optind;
+ argv += optind;
+
+ switch (argc) {
+ case 0:
+ fp = stdout;
+ break;
+ case 1:
+ fp = fopen(argv[0], append_opt ? "a" : "w");
+ if (!fp) {
+ perror(argv[0]);
+ return 1;
+ }
+ break;
+ default:
+ fprintf(stderr, "%s: too many arguments\n", argv[0]);
+ return 1;
+ }
+ setvbuf(fp, NULL, _IOLBF, 0);
+
+ if (ignore)
+ ignore--;
+ else
+ eol = 1;
+
+ while ((c = getchar()) != EOF) {
+ if (c == '\n') {
+ if (ignore)
+ ignore--;
+ else
+ eol = 1;
+ } else if (eol) {
+ struct timeval tv;
+ struct tm *tm;
+ size_t sz;
+ char *start, *p;
+
+ gettimeofday(&tv, NULL);
+ tm = (utc_opt ? gmtime : localtime)(&tv.tv_sec);
+ sz = strftime(buf, sizeof(buf), fmt, tm);
+ if (sz == 0 || sz == sizeof(buf)) {
+ strcpy(buf, "[OVERFLOW]: ");
+ sz = strlen(buf);
+ }
+ start = buf;
+ while ((p = strstr(start, "%@")) != NULL) {
+ fwrite(start, 1, p - start, fp);
+ fprintf(fp, "%06d", tv.tv_usec);
+ sz -= p - start + 2;
+ start = p + 2;
+ }
+ fwrite(start, 1, sz, fp);
+ eol = 0;
+ }
+ fputc(c, fp);
+ }
+ fclose(fp);
+ return 0;
+}

Return to:

Send suggestions and report system problems to the System administrator.