From ff65df1228d77143a806a37f75f10c06ad17df79 Mon Sep 17 00:00:00 2001 From: Tom Smeding Date: Thu, 8 Jun 2023 10:18:11 +0200 Subject: Allow printing timestamps with -s --- .gitignore | 1 + main.cpp | 38 +++++++++++++++++++++++++++++++++----- 2 files changed, 34 insertions(+), 5 deletions(-) diff --git a/.gitignore b/.gitignore index 38a0404..6b106b0 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ /obj datetags +.ccls-cache/ diff --git a/main.cpp b/main.cpp index 51262e9..047b556 100644 --- a/main.cpp +++ b/main.cpp @@ -3,17 +3,45 @@ #include -int main() { +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); - const struct tm *tm = localtime(&tv.tv_sec); - char buffer[128]; - const ssize_t nw = - strftime(buffer, sizeof buffer - 7, "%Y-%m-%d %H:%M:%S.", tm); + 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++) { -- cgit v1.2.3-70-g09d2