Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 4.20 futimens,utimensat,andutimesFunctions 127


•Iftimesis a non-null pointer and bothtv_nsecfields areset toUTIME_OMIT,
no permissions checks areperformed.

Withfutimens,you need to open the file to change its times. Theutimensat
function provides a way to change a file’s times using the file’s name. Thepathname
argument is evaluated relative to thefdargument, which is either a file descriptor of an
open directory or the special valueAT_FDCWDto force evaluation relative to the current
directory of the calling process. Ifpathnamespecifies an absolute pathname, then thefd
argument is ignored.
Theflag argument toutimensat can be used to further modify the default
behavior.IftheAT_SYMLINK_NOFOLLOWflag is set, then the times of the symbolic link
itself arechanged (if the pathname refers to a symbolic link). The default behavior is to
follow a symbolic link and modify the times of the file to which the link refers.
Bothfutimens and utimensat areincluded in POSIX.1. Athirdfunction,
utimes, is included in the Single UNIX Specification as part of the XSI option.
#include <sys/time.h>
int utimes(const char *pathname,const struct timevaltimes[2]);
Returns: 0 if OK,−1 on error
Theutimesfunction operates on a pathname. Thetimesargument is a pointer to
an array of two timestamps—access time and modification time—but they are
expressed in seconds and microseconds:

struct timeval {
time_t tv_sec; /* seconds */
long tv_usec; /* microseconds */
};

Note that we areunable to specify a value for the changed-status time,
st_ctim—the time the i-node was last changed—asthis field is automatically updated
when theutimefunction is called.
On some versions of the UNIX System, thetouch( 1 )command uses one of these
functions. Also, the standardarchive programs,tar( 1 )andcpio( 1 ),optionally call
these functions to set a file’s times to the time values saved when the file was archived.

Example


The program shown in Figure4.21 truncates files to zerolength using theO_TRUNC
option of theopenfunction, but does not change their access time or modification time.
To dothis, the program first obtains the times with thestatfunction, truncates the file,
and then resets the times with thefutimensfunction.
#include "apue.h"
#include <fcntl.h>

int
main(int argc, char *argv[])
Free download pdf