Example (utime -- Set Modification Time)

This example sets the last modification time of file utime.dat to the current time. It prints an error message if it cannot.

#include <sys\types.h>
#include <sys\utime.h>
#include <sys\stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define  FILENAME      "utime.dat"
int main(void)
{
   struct utimbuf ubuf;
   struct stat statbuf;
   FILE *fp;                                              /* File pointer     */
   /* creating file, whose date will be changed by calling utime              */
   fp = fopen(FILENAME, "w");
   /* write Hello World in the file                                           */
   fprintf(fp, "Hello World\n");
   /* close file                                                              */
   fclose(fp);
   /* seconds to Fri Dec 31 23:59:58 1999 from 1970 Jan 1                     */
   ubuf.modtime = 946702799;
   ubuf.actime  = 946702799;
   /* changing file modification time                                         */
   if (-1 == utime(FILENAME, &ubuf)) {
      perror("utime failed");
      remove(FILENAME);
      return EXIT_FAILURE;
   }
   /* display the modification time                                           */
   if (0 == stat(FILENAME, &statbuf)) {
      printf("The file modification time is: %s\n", ctime(&statbuf.st_mtime));
   }
   else
      printf("File could not be found\n");
   remove(FILENAME);
   return 0;
   /****************************************************************************
      The output should be similar to:
      The file modification time is: Fri Dec 31 23:59:58 1999
   ****************************************************************************/
}