How do I manipulate the contents of a stat() struct?

I have a stat struct, and I'm looking for a way to get data out of it to be manipulated. The program will successfully run and print the desired st_mtime value, but including either of the "seg-fault" lines below causes a segmentation fault in runtime.

        struct stat buf;
        time_t time_m;
        time_t sys_time = time(0);
        if(stat(sub_dirp->d_name,&buf)==0)
                 {
                     //time_m = buf.st_mtime;                                     //seg-fault
                     //double since_last = (difftime(sys_time, buf.st_mtime)/60); //seg-fault
                     printf("%d ", (int)buf.st_mtime);                          //This works.
                 }

Both lines are attempting to manipulate the buf.st_mtime value in some way.

I've had a hard time finding any examples of the usage of stat() that do anything other than print its contents, which makes me wonder if it's even possible.

So my question is, if it is possible, what am I missing?

P.S. I do wish to keep st_mtime in the Unix timestamp format to make it easier to manipulate.

Edit: After realizing that st_mtime is itself its own struct (timespec), how can I access the st_mtime.tv_sec member?

The compiler doesn't like buf.st_mtime.tv_sec one bit.

compiler error

1 answer

  • answered 2022-05-07 19:10 jettg

    For anyone who was stumped by this, I ended up achieving my desired result by creating a timespec struct:

    struct timespec tspec;
    

    This subsequently allowed me to make these two assignments:

    tspec.tv_sec = buf.st_mtime;
    time_t time_m = tspec.tv_sec; //tv_sec is of type time_t
    

    Then I can manipulate time_m however I please. Although I must admit I'm still not sure why you can't assign time_m directly to buf.st_mtime if doing it with a "middleman" works just fine.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum