Search code examples
clinuxunixoperating-systemstat

Format specifier for printing contents of "stat" buffer


I used the stat() function on linux to retrieve details about a file.
One of the details is time of last access stored in variable "st_atime"
But what is the format specifier to display this detail.My program keeps throwing errors.

#include<stdio.h>
#include<sys/stat.h>

int main()
{
  struct stat buf;
  stat("reversi.py",&buf);
  printf("The size  is...%d\n",buf.st_atime);
  return 0;
}

The error is

warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘__time_t’ [-Wformat=]
     printf("The size  is...%d\n",buf.st_atime);

What is the correct format specifier for this kind of data.
Also there are several more details returned by the function.Is there a place where i could find all the correct format specifiers for these details.?
Thank You.


Solution

  • The ctime(), gmtime() and localtime() functions all takes time_t data type.

    #include <stdio.h>
    #include <stdlib.h>
    #include <sys/types.h>
    #include <unistd.h>
    #include<sys/stat.h>
    #include <time.h>
    
    int main()
    {
        struct stat buf;
        stat("1.c",&buf);
        printf("Last Access was :  %s\n",ctime(&buf.st_atime));
        return 0;
    }
    

    this will print

    Last Access was :  Tue Apr 28 10:09:15 2015