C Linux stat() getting atime/mtime with nsec precision
c, linux, stat, variables
Solution
- `st_mtime` should be a `time_t`.
- According to POSIX `<time.h>`, the type of `tv_nsec` is just `long`.
- The fields like `st_mtim.tv_nsec` will return the number of nanoseconds.
- For the `long`, you need `l`; for `time_t`, it is not clearly defined, AFAIK.
Problem
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