File modification time

From Rosetta Code

Jump to: navigation, search
File modification time is a programming task. Visitors like you are encouraged to solve it according to the task description, using any language they may happen to know.
Add to BlogMarksAdd to del.icio.usAdd to diggAdd to NewsvineAdd to redditAdd to Slashdot

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

Phobos (the standard library provided by Digital Mars) does not provide a facility to set the last modification time.

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
}

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

Alternative (only gets modification time):

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

[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

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
Google AdSense