#include #include #include static void print_usage(const char *argv0) { std::cerr << "Usage: " << argv0 << " [OPTIONS]\n" << " -h Show this help\n" << " -d Print deltas in seconds, not timestamps\n" << " -s Print tags in timestamp format\n" << " -t Print tags in local time format (default)\n" << std::flush; } enum Mode { M_STAMP, M_LOCALTIME, M_DELTA, }; int main(int argc, char **argv) { // use std::cin, stdout, std::cerr std::ios::sync_with_stdio(false); Mode mode = M_LOCALTIME; 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 'd': mode = M_DELTA; break; case 's': mode = M_STAMP; break; case 't': mode = M_LOCALTIME; break; default: print_usage(argv[0]); return 1; } } } struct timeval tv; double prevtm; if (mode == M_DELTA) { gettimeofday(&tv, nullptr); prevtm = tv.tv_sec + tv.tv_usec * 1.0e-6; } std::string line; while (std::getline(std::cin, line)) { gettimeofday(&tv, nullptr); switch (mode) { case M_STAMP: printf("%.6lf %s\n", tv.tv_sec + tv.tv_usec * 1.0e-6, line.data()); break; case M_LOCALTIME: { const struct tm *tm = localtime(&tv.tv_sec); char buffer[128]; ssize_t nw = strftime(buffer, sizeof buffer - 7, "%Y-%m-%d %H:%M:%S.", tm); for (int i = 5; i >= 0; i--) { buffer[nw + i] = '0' + tv.tv_usec % 10; tv.tv_usec /= 10; } buffer[nw + 6] = '\0'; printf("%s %s\n", buffer, line.data()); break; } case M_DELTA: { double tm = tv.tv_sec + tv.tv_usec * 1.0e-6; printf("%.6lf %s\n", tm - prevtm, line.data()); prevtm = tm; break; } } } }