Ad

Setting File Access Time, Modification Time

- 1 answer

I have a list of files in a mounted drive. I am trying to set access and modify time.

This is the stat information before using utime to modify

Access: 2020-07-28 15:06:51.000000000 +0530
Modify: 2020-07-28 15:06:51.000000000 +0530

After using utime here is the stat information.

Access: 2020-07-28 21:20:47.-469639744
Modify: 2020-07-28 21:20:47.-469740064

Here is the code

#include <stdio.h>
#include <utime.h>
#include <time.h>
#include <string.h>
#include <errno.h>

int main(void) {
    const char *filepath = "pathToFile/file";
    struct utimbuf ubuf;
    ubuf.actime = time(NULL) + (time_t)(6*60*60);
    ubuf.modtime = time(NULL) + (time_t)(6*60*60);
    errno = 0;
    int ret = utime(filepath, &ubuf);
    if (ret == -1) {
        printf("Error is: %s\n", strerror(errno));
    } else {
        puts("No Error!");
    }
    return 0;
}

How do I retain the time zone info of +0530 here?

Ad

Answer

There is no time zone info stored in file timestamps (at least not in a filesystems I worked with). It's just stat is displaying it that way.

The relevant code from stat.chuman_time():

  if (localtime_rz (tz, &t.tv_sec, &tm))
    nstrftime (str, sizeof str, "%Y-%m-%d %H:%M:%S.%N %z", &tm, tz, ns);
  else
    {
      char secbuf[INT_BUFSIZE_BOUND (intmax_t)];
      sprintf (str, "%s.%09d", timetostr (t.tv_sec, secbuf), ns);
    }

Internally all stat "knows" is the timestamp of the file in struct timespec format without any timezone information. If the conversion from seconds from the file timestamp to struct tm in localtime_rz() call succeeds, then the timestamp is printed in a format that includes the %z timezone information. If the call fails, then "%s.%09d" is used. The timestamp is not stored, it is inferred ("guessed") from the stamp when stat displays info about the file.

Ad
source: stackoverflow.com
Ad