batfastad
batfastad

Reputation: 2013

C Linux stat() getting atime/mtime with nsec precision

Learning C and I'm trying to get a visual comparison of the variable types and sizes that are returned by stat() for the atime/mtime attributes and for the nsec precision values.

I'm running stat() on a file and want to get the mtime and mtime nsec values from the returned stat structure and then store these values in separate variables (which I then want to pass to utimes()... long story!).
According to http://www.kernel.org/doc/man-pages/online/pages/man2/stat.2.html#NOTES I can get the value from st_mtim.tv_nsec or st_mtimensec depending on various OS/build conditions. In my actual program I'll check for both and use whichever is set, or just fallback to the normal second precision of st_mtime

What variable type and size do I need to declare in order to store a normal timestamp as returned by st_mtime?

What variable type and size do I need to declare to store an nsec value from st_mtim.tv_nsec or st_mtimensec?
Are these a decimal, including the number of whole seconds of the time? Or do they just return the nsec portion of the time?

Do I need to declare different variable sizes for the nsecs depending on my system's architecture?

And finally, what conversion specifiers do I need for outputting these variables using printf()?

Cheers, B

Upvotes: 3

Views: 5438

Answers (2)

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215259

st_mtim.tv_nsec is always in the range [0,999999999]. You need to get the seconds from tv_sec. In theory you could multiply seconds by 1000000000 and store them together in a 64-bit value, but it will overflow in a couple hundred years or so.

Upvotes: 1

Jonathan Leffler
Jonathan Leffler

Reputation: 753725

  1. st_mtime should be a time_t.
  2. According to POSIX <time.h>, the type of tv_nsec is just long.
  3. The fields like st_mtim.tv_nsec will return the number of nanoseconds.
  4. For the long, you need l; for time_t, it is not clearly defined, AFAIK.

Upvotes: 4

Related Questions