0

I'm writing a program in C. I want to get the current hour,minute, second, and nanosecond in the form of H:M:S:3N. Basically. echo "$(date +' %H:%M:%S:%3N')" command does what I want. How can I execute it in my C code and print the result?

Any help is appreciated!

Andy Lester
  • 91,102
  • 13
  • 100
  • 152
  • You should start with "How to get the time in C." Look here for inspiration: https://stackoverflow.com/questions/5141960/get-the-current-time-in-c – h0r53 Nov 29 '21 at 16:23
  • 3
    By the way, your question isn't really "How to execute a terminal command in C?" - It's moreso, "How to print the current time in C?" In general, you shouldn't execute terminal commands in C. You should use functionally equivalent library functions to reproduce the behavior you see in other programs such as `date`. – h0r53 Nov 29 '21 at 16:26
  • If you want to get the current hour, minute, second, and nanosecond, you can call the clock_gettime() function. If you want to execute the 'date' command from your code and capture the output, you can use popen() and pclose(). – Michael Walsh Pedersen Nov 29 '21 at 16:52

1 Answers1

1

You are looking for strftime. eg:

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>

int
main(int argc, char **argv)
{
    int rv = EXIT_SUCCESS;
    struct timeval tv;
    struct tm *tm;
    char *default_args[] = { "%H:%M:%S %B %d, %Y", NULL };
    if( gettimeofday(&tv, NULL) == -1 ){
        perror("gettimeofday");
        exit(1);
    }
    argv = argc < 2 ? default_args : argv + 1;
    tm = gmtime(&tv.tv_sec);
    for( ; *argv; argv += 1 ){
        char buf[1024];
        const char *fmt = *argv;
        if( strftime(buf, sizeof buf, fmt, tm) ){
            printf("%s\n", buf);
        } else {
            fprintf(stderr, "Error formatting %s\n", fmt);
            rv = EXIT_FAILURE;
        }
    }
    return rv;
}

Note that %N is not generally supported by strftime, so you'll have to parse nano seconds manually.

William Pursell
  • 204,365
  • 48
  • 270
  • 300