File modification time

From Rosetta Code
Revision as of 22:02, 10 October 2009 by Ulrie (talk | contribs)
Task
File modification time
You are encouraged to solve this task according to the task description, using any language you may know.

This task will attempt to get and set the modification time of a file.

Ada

Ada does not allow you to change the date of a file but you can definitely read it: <lang ada>with Ada.Directories; use Ada.Directories; with Ada.Text_IO; use Ada.Text_IO; with Ada.Calendar.Formatting; use Ada.Calendar.Formatting;

procedure File_Time_Test is begin

  Put_Line (Image (Modification_Time ("file_time_test.adb")));

end File_Time_Test;</lang>

AutoHotkey

<lang AutoHotkey> FileGetTime, OutputVar, output.txt MsgBox % OutputVar FileSetTime, 20080101, output.txt FileGetTime, OutputVar, output.txt MsgBox % OutputVar </lang>

C

POSIX: <lang c>#include <time.h>

  1. include <utime.h>
  2. include <sys/stat.h>

const char *filename = "input.txt";

int main() {

 struct stat foo;
 time_t mtime;
 struct utimbuf new_times;
 stat(filename, &foo);
 mtime = foo.st_mtime; /* seconds since the epoch */
 new_times.actime = foo.st_atime; /* keep atime unchanged */
 new_times.modtime = time(NULL);    /* set mtime to current time */
 utime(filename, &new_times);
 return 0;

}</lang>

C++

compiled with g++ -lboost_filesystem <sourcefile> -o <destination file> <lang c++>#include <boost/filesystem/operations.hpp>

  1. include <ctime>
  2. include <iostream>

int main( int argc , char *argv[ ] ) {

  if ( argc != 2 ) {
     std::cerr << "Error! Syntax: moditime <filename>!\n" ;
     return 1 ;
  }
  boost::filesystem::path p( argv[ 1 ] ) ;
  if ( boost::filesystem::exists( p ) ) {
     std::time_t t = boost::filesystem::last_write_time( p ) ;
     std::cout << "On " << std::ctime( &t ) << " the file " << argv[ 1 ] 

<< " was modified the last time!\n" ;

     std::cout << "Setting the modification time to now:\n" ;
     std::time_t n = std::time( 0 ) ;
     boost::filesystem::last_write_time( p , n ) ; 
     t = boost::filesystem::last_write_time( p ) ;
     std::cout << "Now the modification time is " << std::ctime( &t ) << std::endl ;
     return 0 ;
  } else {
     std::cout << "Could not find file " << argv[ 1 ] << '\n' ;
     return 2 ;
  }

}</lang>

Common Lisp

Common Lisp doesn't provide a way to set the modification time. The write date can be accessed, however, using file-write-date:

<lang lisp>(file-write-date "input.txt")</lang>

Implementations may, in addition, provide other ways of accessing these file attributes, e.g., POSIX bindings:

Works with: SBCL

(1.0.30, OS X, Intel),

Translation of: C

(sb-posix:utime takes an access time and a modification time rather than an array of two times.)

<lang lisp>(let* ((filename "input.txt")

      (stat (sb-posix:stat filename))
      (mtime (sb-posix:stat-mtime stat)))
 (sb-posix:utime filename

(sb-posix:stat-atime stat) (sb-posix:time)))</lang>

D

Phobos (the standard library provided by Digital Mars) does not provide a facility to set the last modification time. <lang d> import std.time; import std.file; void main() {

 d_time modtime,tmp;
 getTimes("input.txt",tmp,tmp,modtime);
 // modtime now contains a representation of the last modified time, convertible using functions from std.time

} </lang>

E

Works with: E-on-Java
Translation of: Java

E follows the Java File interface, except that it replaces boolean success/failure returns with an ejector parameter, so that the default behavior if the client does not handle the case is not to continue ignoring the failure.

<lang e>def strdate(date) {

 return E.toString(<unsafe:java.util.makeDate>(date))

}

def test(type, file) {

   def t := file.lastModified()
   println(`The following $type called ${file.getPath()} ${
           if (t == 0) { "does not exist." } else { `was modified at ${strdate(t)}` }}`)
   println(`The following $type called ${file.getPath()} ${
           escape ne { file.setLastModified(timer.now(), ne); "was modified to current time." } catch _ { "does not exist." }}`)
   println(`The following $type called ${file.getPath()} ${
           escape ne { file.setLastModified(t, ne); "was modified to previous time." } catch _ { "does not exist." }}`)

}

test("file", <file:output.txt>) test("directory", <file:docs>)</lang>

Haskell

<lang haskell>import System.Posix.File import System.Posix.Time

do status <- getFileStatus filename

  let atime = accessTime status
      mtime = modificationTime status -- seconds since the epoch
  curTime <- epochTime
  setFileTimes filename atime curTime -- keep atime unchanged
                                      -- set mtime to current time</lang>

Alternative (only gets modification time): <lang haskell>import System.Directory import System.Time

do ct <- getModificationTime filename

  cal <- toCalendarTime ct
  putStrLn (calendarTimeToString cal)</lang>

J

The standard file access library only supports reading the file modification time. <lang j> load 'files'

  fstamp 'input.txt'

2009 8 24 20 34 30</lang> It is possible to set the time but it has to be done through OS specific external calls.

Java

<lang java>import java.io.File; import java.util.Date; public class FileModificationTimeTest {

  public static void test(String type, File file) {
      long t = file.lastModified();
      System.out.println("The following " + type + " called " + file.getPath() +
           (t == 0 ? " does not exist." : " was modified at " + new Date(t).toString() )
      );
      System.out.println("The following " + type + " called " + file.getPath() + 
           (!file.setLastModified(System.currentTimeMillis()) ? " does not exist." : " was modified to current time." )
      );
      System.out.println("The following " + type + " called " + file.getPath() + 
           (!file.setLastModified(t) ? " does not exist." : " was modified to previous time." )
      );
  }
  public static void main(String args[]) {
      test("file", new File("output.txt"));
      test("directory", new File("docs"));
  }

}</lang>

JavaScript

Works with: JScript

Get only. <lang javascript>var fso = new ActiveXObject("Scripting.FileSystemObject"); var f = fso.GetFile('input.txt'); var mtime = f.DateLastModified;</lang>

Mathematica

Get file modification time: <lang Mathematica> FileDate["file","Modification"]</lang> results is returned in format: {year,month,day,hour,minute,second}. Setting file modification time: <lang Mathematica> SetFileDate["file",date,"Modification"]</lang> where date is specified as {year,month,day,hour,minute,second}.

MAXScript

MAXScript has no method to set the mod time

-- Returns a string containing the mod date for the file, e.g. "1/29/99 1:52:05 PM"
getFileModDate "C:\myFile.txt"

Objective-C

<lang objc>NSFileManager *fm = [NSFileManager defaultManager];

NSLog(@"%@", [[fm fileAttributesAtPath:@"input.txt" traverseLink:YES] fileModificationDate]);

[fm changeFileAttributes:[NSDictionary dictionaryWithObject:[NSDate date] forKey:NSFileModificationDate]

                 atPath:@"input.txt"];</lang>

OCaml

<lang ocaml>#load "unix.cma";; open Unix;; let mtime = (stat filename).st_mtime;; (* seconds since the epoch *)

utimes filename (stat filename).st_atime (time ());; (* keep atime unchanged

  set mtime to current time *)</lang>

Perl

Works with: Perl version 5

<lang perl>use File::stat qw(stat); my $mtime = stat($file)->mtime; # seconds since the epoch

utime(stat($file)->atime, time, $file);

  1. keep atime unchanged
  2. set mtime to current time</lang>

PHP

<lang php><?php $filename = 'input.txt';

$mtime = filemtime($filename); // seconds since the epoch

touch($filename,

     time(), // set mtime to current time
     fileatime($filename)); // keep atime unchanged

?></lang>

Pop11

<lang pop11>;;; Print modification time (seconds since Epoch) sysmodtime('file') =></lang>

PowerShell

<lang powershell>$modificationTime = (Get-ChildItem file.txt).LastWriteTime Set-ItemProperty file.txt LastWriteTime (Get-Date)</lang>

Python

<lang python>import os

  1. Get modification time:

modtime = os.path.getmtime('filename')

  1. Set the access and modification times:

os.utime('path', (actime, mtime))

  1. Set just the modification time:

os.utime('path', (os.path.getatime('path'), mtime))

  1. Set the access and modification times to the current time:

os.utime('path', None)</lang>

R

See this R-devel mailing list thread for more information. <lang r>

  1. Get the value

file.info(filename)$mtime

  1. To set the value, we need to rely on shell commands. The following works under windows.

shell("copy /b /v filename +,,>nul")

  1. and on Unix (untested)

shell("touch -m filename") </lang>

RapidQ

<lang rapidq>name$ = DIR$("input.txt", 0) PRINT "File date: "; FileRec.Date PRINT "File time: "; FileRec.Time</lang>

Ruby

<lang ruby>#Get modification time: modtime = File.mtime('filename')

  1. Set the access and modification times:

File.utime(actime, mtime, 'path')

  1. Set just the modification time:

File.utime(File.atime('path'), mtime, 'path')

  1. Set the access and modification times to the current time:

File.utime(nil, nil, 'path')</lang>

Slate

Modifying the timestamp value is not currently a built-in feature. This code gets a raw value:

<lang slate> slate[1]> (File newNamed: 'LICENSE') fileInfo modificationTimestamp. 1240349799 </lang>

Smalltalk

<lang smalltalk>|a| a := File name: 'input.txt'. (a lastModifyTime) printNl.</lang>

Standard ML

<lang sml>val mtime = OS.FileSys.modTime filename; (* returns a Time.time data structure *)

(* unfortunately it seems like you have to set modification & access times together *) OS.FileSys.setTime (filename, NONE); (* sets modification & access time to now *) (* equivalent to: *) OS.FileSys.setTime (filename, SOME (Time.now ()))</lang>

Tcl

Assuming that the variable filename holds the name of the file... <lang tcl># Get the modification time: set timestamp [file mtime $filename]

  1. Set the modification time to ‘now’:

file mtime $filename [clock seconds]</lang>

Vedit macro language

Display file's last modification time as number of seconds since midnight. <lang vedit>Num_Type(File_Stamp_Time("input.txt"))</lang>

Displays file's last modification date and time as a string. <lang vedit>File_Stamp_String(10, "input.txt") Reg_Type(10)</lang> Vedit Macro Language has no method to set the modification time

Visual Basic .NET

Platform: .NET

Works with: Visual Basic .NET version 9.0+

<lang vbnet>Dim file As New IO.FileInfo("test.txt")

'Creation Time Dim createTime = file.CreationTime file.CreationTime = createTime.AddHours(1)

'Write Time Dim writeTime = file.LastWriteTime file.LastWriteTime = writeTime.AddHours(1)

'Access Time Dim accessTime = file.LastAccessTime file.LastAccessTime = accessTime.AddHours(1)</lang>