-1
struct stat {
dev_t     st_dev;     /* ID of device containing file */
ino_t     st_ino;     /* inode number */
mode_t    st_mode;    /* protection */
nlink_t   st_nlink;   /* number of hard links */
uid_t     st_uid;     /* user ID of owner */
gid_t     st_gid;     /* group ID of owner */
dev_t     st_rdev;    /* device ID (if special file) */
off_t     st_size;    /* total size, in bytes */
blksize_t st_blksize; /* blocksize for file system I/O */
blkcnt_t  st_blocks;  /* number of 512B blocks allocated */
time_t    st_atime;   /* time of last access */
time_t    st_mtime;   /* time of last modification */
time_t    st_ctime;   /* time of last status change */
}

I am working with the stat struct in C and I want to output each of the fields. When I try to output st_atime, st_mtime, and st_ctime I am using the following lines:

    printf("Last file change: %s\n", ctime(sb.st_ctime));
    printf("Last file access time: %s\n", ctime(sb.st_atime));
    printf("Last file mod time: %s\n", ctime(sb.st_mtime));

For some reason, I am getting a Segmentation Fault(Core Dump) error. My declaration for the stat struct is:

struct stat sb;

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

char file[128];

int main(int argc, char *argv[]){
struct stat sb;

sprintf(file, "%s", argv[1]);


if(stat(file, &sb) == 0)
 {
 printf("Last change: %s\n", ctime(sb.st_ctime));
 printf("Last File access: %s\n", ctime(sb.st_atime));
 printf("Last file mod: %s\n", ctime(sb.st_mtime));
  }
else
 {
   printf("File name does not exist!\n");
 }

return 0;
 }
Cœur
  • 37,241
  • 25
  • 195
  • 267
j1nrg
  • 69
  • 7

2 Answers2

0

You should pass reference to ctime according to its documentation so I suggest to use:

printf("Last file change: %s\n", ctime(&sb.st_ctime));
printf("Last file access time: %s\n", ctime(&sb.st_atime));
printf("Last file mod time: %s\n", ctime(&sb.st_mtime));
Pooya
  • 6,083
  • 3
  • 23
  • 43
0

EDIT: To use the function ctime you should include time.h library using

#include <time.h>

The function ctime receives a pointer to a time_t.

char* ctime (const time_t * timer);

You are passing the time_t itself. You should pass the address of your struct or change the time to time_t * in your struct. This approach is dangerous depending where you are declaring your struct.

printf("Last file change: %s\n", ctime(&(sb.st_ctime)));

or change the declaration to

time_t*    st_ctime;   /* time of last status change */