Modifying a File's Timestamps

The struct stat contains the fields st_atime and st_mtime, among other

things. st_atime indicates the most recent access time of a file (read

how to retrieve a file's information into a struct stat and how to

interpret it here: http://www.itworld.com/nl/lnx_tip/07272001). This

value is updated whenever the file is opened or its inode is modified.

The st_mtime field contains the most recent modification time of a

file. It's updated whenever the file's data has changed.

Certain applications need to change these attributes. Tools such as tar

and cpio for instance reset the file's atime and mtime timestamps to

the values they had when the file was archived. User programs that

recover files from a backup set may also need to change the values of

these fields (note that the field st_ctime is automatically updated

whenever you change st_atime or st_mtime so you can use it to detect

unauthorized changes in a file's timestamps).

The utime() and utimes() Functions

Linux supports two syscalls that change the values of atime and mtime,

namely utime() and utimes(). utime() is defined by the POSIX standard

so, in general, you should prefer it to utimes(). utimes() has

historical significance: it was originally defined by BSD so you may

still find it in legacy code and in application ported from BSD. In

terms of functionality, they are both identical. They only differ in

their parameter lists and the locations of their prototypes.

The function utime() is declared in

and has the following prototype: int utime(const char * pathname, struct utimbuf * buf); Where struct utimbuf is defined as follows: struct utimbuf { time_t actime; time_t modtime; }; The utimes() function is declared in the header as follows: int utimes(const char* pathname, struct timeval * tv); Where struct timeval is defined as follows: struct timeval { long tv_sec; long tv_usec; }; The members tv_sec and usec contain the new values for atime and mtime, respectively. As a special case, passing a NULL pointer as the second argument of either function sets both fields to the current timestamp. As always, the timestamps are represented as the number of seconds elapsed since the Epoch.
From CIO: 8 Free Online Courses to Grow Your Tech Skills
Join the discussion
Be the first to comment on this article. Our Commenting Policies