user997112
user997112

Reputation: 30625

snprintf not printing out a converted timeval using strftime?

I have taken this answer from SO:

https://stackoverflow.com/a/2409054/997112

so that I can print timeval structs in a friendly format. I had to change "%s.%06d" for "%s.%06ld" because I was getting compiler warnings:

void printTimeval(struct timeval& tv){

    time_t nowtime;
    struct tm *nowtm;
    char tmbuf[64], buf[64];

    nowtime = tv.tv_sec;
    nowtm = localtime(&nowtime);

    strftime(tmbuf, sizeof tmbuf, "%Y-%m-%d %H:%M:%S", nowtm);
    snprintf(buf, sizeof buf, "%s.%06ld", tmbuf, tv.tv_usec);
}

However, when I pass a valid time nothing prints.

I checked the number of seconds in the timeval I passed-in, before calling my function and it returns 1404120855, so I am confident my timeval is correct and the problem lies with the function?

Upvotes: 0

Views: 375

Answers (1)

unwind
unwind

Reputation: 399959

All snprintf() does is format a string. You never actually print out the resulting string in buf. Add something like:

printf("%s\n", buf);

or

puts(buf);

Also, you should have a cast to long for that tv_usec field, since you can't know the type of the typedef to be long.

Upvotes: 1

Related Questions