File modification time

From Rosetta Code

Jump to: navigation, search
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.

Contents

[edit] Ada

Ada does not allow you to change the date of a file but you can definitely read it:

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;

[edit] AutoHotkey

FileGetTime, OutputVar, output.txt
MsgBox % OutputVar
FileSetTime, 20080101, output.txt
FileGetTime, OutputVar, output.txt
MsgBox % OutputVar

[edit] Batch File

Works with: Windows NT version 4

for %%f in (file.txt) do echo.%%~tf

The date/time format is dependent on the user's locale, like the contents of the %DATE% and %TIME% built-ins. There is no built-in way of setting a file's modification time.

[edit] C

POSIX:

#include <time.h>
#include <utime.h>
#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;
}

[edit] C++

compiled with g++ -lboost_filesystem <sourcefile> -o <destination file>

#include <boost/filesystem/operations.hpp>
#include <ctime>
#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 ;
}
}

[edit] C#

using System;
using System.IO;
 
Console.WriteLine(File.GetLastWriteTime("file.txt"));
File.SetLastWriteTime("file.txt", DateTime.Now);

[edit] Clojure

(import '(java.io File)
'(java.util Date))
 
(Date. (.lastModified (File. "output.txt")))
(Date. (.lastModified (File. "docs")))
 
(.setLastModified (File. "output.txt")
(.lastModified (File. "docs")))

[edit] 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:

(file-write-date "input.txt")

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.)

(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)))

[edit] D

Works with: D version 2

import std.file: getTimes, setTimes, d_time;
 
void main() {
d_time creation_time, access_time, modified_time;
getTimes("data.txt", creation_time, access_time, modified_time);
setTimes("data.txt", access_time, modified_time);
}

[edit] 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.

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>)

[edit] Factor

"foo.txt" file-info modified>> .

Setting the modified time is not cross-platform, so here's a Unix version.

USE: io.files.info.unix
 
"foo.txt" now 2 hours time+ set-file-modified-time

[edit] Go

package main
import "fmt"
import "os"
import "time"
 
var filename = "input.txt"
 
func main() {
foo, _ := os.Stat(filename)
fmt.Println(foo.Mtime_ns) // nanoseconds since the epoch
 
os.Chtimes(filename,
foo.Atime_ns, // keep atime unchanged
time.Nanoseconds()) // set mtime to current time
}

[edit] Haskell

import System.Posix.Files
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

Alternative (only gets modification time):

import System.Directory
import System.Time
 
do ct <- getModificationTime filename
cal <- toCalendarTime ct
putStrLn (calendarTimeToString cal)

[edit] HicEst

CHARACTER timestamp*18
 
timestamp = ' ' ! blank timestamp will read:
SYSTEM(FIle="File_modification_time.hic", FileTime=timestamp) ! 20100320141940.525
 
timestamp = '19991231235950' ! set timestamp to Millenium - 10 seconds
SYSTEM(FIle="File_modification_time.hic", FileTime=timestamp)

[edit] Icon and Unicon

[edit] Icon

Icon doesn't support 'stat' or 'utime'; however, information can be obtained by use of the system function to access command line.

[edit] Unicon

 
every dir := !["./","/"] do {
if i := stat(f := dir || "input.txt") then {
write("info for ",f ," mtime= ",ctime(i.mtime),", atime=",ctime(i.ctime), ", atime=",ctime(i.atime))
utime(f,i.atime,i.mtime-1024)
i := stat(f)
write("update for ",f ," mtime= ",ctime(i.mtime),", atime=",ctime(i.ctime), ", atime=",ctime(i.atime))
}
else stop("failure to stat ",f)
}

Notes:

  • Icon and Unicon accept both / and \ for directory separators.
  • 'ctime' formats an integer representing an epoch time into human readable form
  • 'utime' updates the atime and mtime values

[edit] J

The standard file access library only supports reading the file modification time.

   load 'files'
fstamp 'input.txt'
2009 8 24 20 34 30

It is possible to set the time but it has to be done through OS specific external calls.

[edit] 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"));
}
}

[edit] JavaScript

Works with: JScript Get only.

var fso = new ActiveXObject("Scripting.FileSystemObject");
var f = fso.GetFile('input.txt');
var mtime = f.DateLastModified;

[edit] Mathematica

Get file modification time:

 FileDate["file","Modification"]

results is returned in format: {year,month,day,hour,minute,second}. Setting file modification time:

 SetFileDate["file",date,"Modification"]

where date is specified as {year,month,day,hour,minute,second}.

[edit] 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"

[edit] Objective-C

NSFileManager *fm = [NSFileManager defaultManager];
 
NSLog(@"%@", [[fm fileAttributesAtPath:@"input.txt" traverseLink:YES] fileModificationDate]);
 
[fm changeFileAttributes:[NSDictionary dictionaryWithObject:[NSDate date] forKey:NSFileModificationDate]
atPath:@"input.txt"];

[edit] 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 *)

[edit] Oz

Getting the modification time:

declare
[Path] = {Module.link ['x-oz://system/os/Path.ozf']}
Modified = {Path.mtime "input.txt"} %% posix time
in
{Show {OsTime.localtime Modified}} %% human readable record

Setting the modification time is not possible, unless implemented as an extension in C or C++.

[edit] Perl

Works with: Perl version 5

my $mtime = (stat($file))[9]; # seconds since the epoch
 
# you should use the more legible version below:
use File::stat qw(stat);
my $mtime = stat($file)->mtime; # seconds since the epoch
 
utime(stat($file)->atime, time, $file);
# keep atime unchanged
# set mtime to current time

[edit] 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
?>

[edit] PicoLisp

(let File "test.file"
(and
(info File)
(prinl (stamp (cadr @) (cddr @))) ) # Print date and time in UTC
(call 'touch File) ) # Set modification time to "now"

Output:

2010-02-20 15:46:37

[edit] Pop11

;;; Print modification time (seconds since Epoch)
sysmodtime('file') =>

[edit] PowerShell

$modificationTime = (Get-ChildItem file.txt).LastWriteTime
Set-ItemProperty file.txt LastWriteTime (Get-Date)

[edit] PureBasic

Debug FormatDate("%yyyy/%mm/%dd", GetFileDate("file.txt",#PB_Date_Modified))
SetFileDate("file.txt",#PB_Date_Modified,Date(1987, 10, 23, 06, 43, 15))
Debug FormatDate("%yyyy/%mm/%dd - %hh:%ii:%ss", GetFileDate("file.txt",#PB_Date_Modified))

[edit] Python

import os
 
#Get modification time:
modtime = os.path.getmtime('filename')
 
#Set the access and modification times:
os.utime('path', (actime, mtime))
 
#Set just the modification time:
os.utime('path', (os.path.getatime('path'), mtime))
 
#Set the access and modification times to the current time:
os.utime('path', None)

[edit] R

See this R-devel mailing list thread for more information.

# Get the value
file.info(filename)$mtime
 
#To set the value, we need to rely on shell commands. The following works under windows.
shell("copy /b /v filename +,,>nul")
# and on Unix (untested)
shell("touch -m filename")

[edit] RapidQ

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

[edit] Ruby

#Get modification time:
modtime = File.mtime('filename')
 
#Set the access and modification times:
File.utime(actime, mtime, 'path')
 
#Set just the modification time:
File.utime(File.atime('path'), mtime, 'path')
 
#Set the access and modification times to the current time:
File.utime(nil, nil, 'path')

[edit] Slate

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

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

[edit] Smalltalk

|a| 
a := File name: 'input.txt'.
(a lastModifyTime) printNl.

[edit] Standard ML

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 ()))

[edit] Tcl

Assuming that the variable filename holds the name of the file...

# Get the modification time:
set timestamp [file mtime $filename]
 
# Set the modification time to ‘now’:
file mtime $filename [clock seconds]

[edit] Vedit macro language

Display file's last modification time as number of seconds since midnight.

Num_Type(File_Stamp_Time("input.txt"))

Displays file's last modification date and time as a string.

File_Stamp_String(10, "input.txt")
Reg_Type(10)

Vedit Macro Language has no method to set the modification time

[edit] Visual Basic .NET

Platform: .NET

Works with: Visual Basic .NET version 9.0+

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)
Personal tools
Support