0

I am using stat to get the last modified time of a file, but I would like to add a few seconds to the overall time.

if (stat(file_path, &st) == 0)
{
    char estimate_time[50];
    strftime(estimate_time, 50, "\'%F %T\'", localtime(&st.st_mtime)
}

So, this code works fine in getting the last modified time of the file, but I would just like to add a few seconds to the overall time. Is there a way to get "st_mtime" in seconds so I can simply add to that value and then use strftime to convert into a formatted output?

Thanks

Dark
  • 323
  • 2
  • 5
  • 13

1 Answers1

1

To portable add a few seconds to a struct tm, simple add to the tm_sec member and call mktime() to normalize the structure.

  struct stat st;
  struct tm *tm = localtime(&st.st_mtime);
  if (tm == NULL) Handle_Error();
  tm->tm_sec += offset;
  time_t time_new = mktime(tm);  // adjust fields.
  if (time_new == (time_t) -1) Handle_Error();
  strftime(estimate_time, sizeof estimate_time, "\'%F %T\'", tm);

Per the [stat] tag, OP is on a POSIX system which requires time_t is in seconds, so POSIX code may add to st.st_mtime.

  time_t new_time = st.st_mtime + offset;
  struct tm *tm = localtime(&new_time);
  if (tm == NULL) Handle_Error();
  strftime(estimate_time, sizeof estimate_time, "\'%F %T\'", tm);
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256