-
-
Notifications
You must be signed in to change notification settings - Fork 693
/
file.d
3626 lines (3046 loc) · 104 KB
/
file.d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Written in the D programming language.
/**
Utilities for manipulating files and scanning directories. Functions
in this module handle files as a unit, e.g., read or write one _file
at a time. For opening files and manipulating them via handles refer
to module $(D $(LINK2 std_stdio.html,std.stdio)).
Macros:
WIKI = Phobos/StdFile
Copyright: Copyright Digital Mars 2007 - 2011.
License: $(WEB boost.org/LICENSE_1_0.txt, Boost License 1.0).
Authors: $(WEB digitalmars.com, Walter Bright),
$(WEB erdani.org, Andrei Alexandrescu),
Jonathan M Davis
Source: $(PHOBOSSRC std/_file.d)
*/
module std.file;
import core.memory;
import core.stdc.stdio, core.stdc.stdlib, core.stdc.string,
core.stdc.errno, std.algorithm, std.array, std.conv,
std.datetime, std.exception, std.format, std.path, std.process,
std.range, std.regexp, std.stdio, std.string, std.traits, std.typecons,
std.typetuple, std.utf;
import std.metastrings; //For generating deprecation messages only. Remove once
//deprecation path complete.
version (Win32)
{
import core.sys.windows.windows, std.windows.charset,
std.windows.syserror, std.__fileinit : useWfuncs;
/*
* Since Win 9x does not support the "W" API's, first convert
* to wchar, then convert to multibyte using the current code
* page.
* (Thanks to yaneurao for this)
*/
version(Windows) alias std.windows.charset.toMBSz toMBSz;
}
else version (Posix)
{
import core.sys.posix.dirent, core.sys.posix.fcntl, core.sys.posix.sys.stat,
core.sys.posix.sys.time, core.sys.posix.unistd, core.sys.posix.utime;
}
else
static assert(false, "Module " ~ .stringof ~ " not implemented for this OS.");
version (unittest)
{
import core.thread : Thread;
private string deleteme()
{
static _deleteme = "deleteme.dmd.unittest";
static _first = true;
if(_first)
{
version(Windows)
_deleteme = std.path.join(std.process.getenv("TEMP"), _deleteme);
else version(Posix)
_deleteme = "/tmp/" ~ _deleteme;
_first = false;
}
return _deleteme;
}
}
// @@@@ TEMPORARY - THIS SHOULD BE IN THE CORE @@@
// {{{
version (Posix)
{
version (OSX)
{
struct struct_stat64 // distinguish it from the stat() function
{
uint st_dev; /// device
ushort st_mode;
ushort st_nlink; /// link count
ulong st_ino; /// file serial number
uint st_uid; /// user ID of file's owner
uint st_gid; /// user ID of group's owner
uint st_rdev; /// if device then device number
int st_atime;
uint st_atimensec;
int st_mtime;
uint st_mtimensec;
int st_ctime;
uint st_ctimensec;
int st_birthtime;
uint st_birthtimensec;
ulong st_size;
long st_blocks; /// number of allocated 512 byte blocks
int st_blksize; /// optimal I/O block size
ulong st_ino64;
uint st_flags;
uint st_gen;
int st_lspare; /* RESERVED: DO NOT USE! */
long st_qspare[2]; /* RESERVED: DO NOT USE! */
}
extern(C) int fstat64(int, struct_stat64*);
extern(C) int stat64(in char*, struct_stat64*);
}
else version (FreeBSD)
{
alias core.sys.posix.sys.stat.stat_t struct_stat64;
alias core.sys.posix.sys.stat.fstat fstat64;
alias core.sys.posix.sys.stat.stat stat64;
alias core.sys.posix.sys.stat.lstat lstat64;
}
else
{
version(X86)
{
struct struct_stat64 // distinguish it from the stat() function
{
ulong st_dev; /// device
uint __pad1;
uint st_ino; /// file serial number
uint st_mode; /// file mode
uint st_nlink; /// link count
uint st_uid; /// user ID of file's owner
uint st_gid; /// user ID of group's owner
ulong st_rdev; /// if device then device number
uint __pad2;
align(4) ulong st_size;
int st_blksize; /// optimal I/O block size
ulong st_blocks; /// number of allocated 512 byte blocks
int st_atime;
uint st_atimensec;
int st_mtime;
uint st_mtimensec;
int st_ctime;
uint st_ctimensec;
ulong st_ino64;
}
//static assert(struct_stat64.sizeof == 88); // copied from d1, but it's currently 96 bytes, not 88.
}
else version (X86_64)
{
struct struct_stat64
{
ulong st_dev;
ulong st_ino;
ulong st_nlink;
uint st_mode;
uint st_uid;
uint st_gid;
int __pad0;
ulong st_rdev;
long st_size;
long st_blksize;
long st_blocks;
long st_atime;
ulong st_atimensec;
long st_mtime;
ulong st_mtimensec;
long st_ctime;
ulong st_ctimensec;
long[3] __unused;
}
static assert(struct_stat64.sizeof == 144);
}
extern(C) int fstat64(int, struct_stat64*);
extern(C) int stat64(in char*, struct_stat64*);
extern(C) int lstat64(in char*, struct_stat64*);
}
}
// }}}
/++
Exception thrown for file I/O errors.
+/
class FileException : Exception
{
/++
OS error code.
+/
immutable uint errno;
/++
Constructor which takes an error message.
Params:
name = Name of file for which the error occurred.
msg = Message describing the error.
file = The file where the error occurred.
line = The line where the error occurred.
+/
this(in char[] name, in char[] msg, string file = __FILE__, size_t line = __LINE__)
{
if(msg.empty)
super(name.idup, file, line);
else
super(text(name, ": ", msg), file, line);
errno = 0;
}
/++
Constructor which takes the error number ($(LUCKY GetLastError)
in Windows, $(D_PARAM getErrno) in Posix).
Params:
name = Name of file for which the error occurred.
msg = Message describing the error.
file = The file where the error occurred.
line = The line where the error occurred.
+/
version(Windows) this(in char[] name,
uint errno = GetLastError,
string file = __FILE__,
size_t line = __LINE__)
{
this(name, sysErrorString(errno), file, line);
this.errno = errno;
}
/++
Constructor which takes the error number ($(LUCKY GetLastError)
in Windows, $(D_PARAM getErrno) in Posix).
Params:
name = Name of file for which the error occurred.
msg = Message describing the error.
file = The file where the error occurred.
line = The line where the error occurred.
+/
version(Posix) this(in char[] name,
uint errno = .getErrno,
string file = __FILE__,
size_t line = __LINE__)
{
auto s = strerror(errno);
this(name, to!string(s), file, line);
this.errno = errno;
}
}
private T cenforce(T)(T condition, lazy const(char)[] name, string file = __FILE__, size_t line = __LINE__)
{
if (!condition)
{
version (Windows)
{
throw new FileException(name, .GetLastError(), file, line);
}
else version (Posix)
{
throw new FileException(name, .getErrno(), file, line);
}
}
return condition;
}
/* **********************************
* Basic File operations.
*/
/********************************************
Read entire contents of file $(D name) and returns it as an untyped
array. If the file size is larger than $(D upTo), only $(D upTo)
bytes are read.
Example:
----
import std.file, std.stdio;
void main()
{
auto bytes = cast(ubyte[]) read("filename", 5);
if (bytes.length == 5)
writefln("The fifth byte of the file is 0x%x", bytes[4]);
}
----
Returns: Untyped array of bytes _read.
Throws: $(D FileException) on error.
*/
void[] read(in char[] name, size_t upTo = size_t.max)
{
version(Windows)
{
alias TypeTuple!(GENERIC_READ,
FILE_SHARE_READ, (SECURITY_ATTRIBUTES*).init, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN,
HANDLE.init)
defaults;
auto h = useWfuncs
? CreateFileW(std.utf.toUTF16z(name), defaults)
: CreateFileA(toMBSz(name), defaults);
cenforce(h != INVALID_HANDLE_VALUE, name);
scope(exit) cenforce(CloseHandle(h), name);
auto size = GetFileSize(h, null);
cenforce(size != INVALID_FILE_SIZE, name);
size = min(upTo, size);
auto buf = GC.malloc(size, GC.BlkAttr.NO_SCAN)[0 .. size];
scope(failure) delete buf;
DWORD numread = void;
cenforce(ReadFile(h,buf.ptr, size, &numread, null) == 1
&& numread == size, name);
return buf[0 .. size];
}
else version(Posix)
{
// A few internal configuration parameters {
enum size_t
minInitialAlloc = 1024 * 4,
maxInitialAlloc = size_t.max / 2,
sizeIncrement = 1024 * 16,
maxSlackMemoryAllowed = 1024;
// }
immutable fd = core.sys.posix.fcntl.open(toStringz(name),
core.sys.posix.fcntl.O_RDONLY);
cenforce(fd != -1, name);
scope(exit) core.sys.posix.unistd.close(fd);
struct_stat64 statbuf = void;
cenforce(fstat64(fd, &statbuf) == 0, name);
//cenforce(core.sys.posix.sys.stat.fstat(fd, &statbuf) == 0, name);
immutable initialAlloc = to!size_t(statbuf.st_size
? min(statbuf.st_size + 1, maxInitialAlloc)
: minInitialAlloc);
auto result = GC.malloc(initialAlloc, GC.BlkAttr.NO_SCAN)
[0 .. initialAlloc];
scope(failure) delete result;
size_t size = 0;
for (;;)
{
immutable actual = core.sys.posix.unistd.read(fd, result.ptr + size,
min(result.length, upTo) - size);
cenforce(actual != -1, name);
if (actual == 0) break;
size += actual;
if (size < result.length) continue;
immutable newAlloc = size + sizeIncrement;
result = GC.realloc(result.ptr, newAlloc, GC.BlkAttr.NO_SCAN)
[0 .. newAlloc];
}
return result.length - size >= maxSlackMemoryAllowed
? GC.realloc(result.ptr, size, GC.BlkAttr.NO_SCAN)[0 .. size]
: result[0 .. size];
}
}
unittest
{
write(deleteme, "1234");
scope(exit) { assert(exists(deleteme)); remove(deleteme); }
assert(read(deleteme, 2) == "12");
assert(read(deleteme) == "1234");
}
version (linux) unittest
{
// A file with "zero" length that doesn't have 0 length at all
auto s = std.file.readText("/proc/sys/kernel/osrelease");
assert(s.length > 0);
//writefln("'%s'", s);
}
/********************************************
Read and validates (using $(XREF utf, validate)) a text file. $(D S)
can be a type of array of characters of any width and constancy. No
width conversion is performed; if the width of the characters in file
$(D name) is different from the width of elements of $(D S),
validation will fail.
Returns: Array of characters read.
Throws: $(D FileException) on file error, $(D UtfException) on UTF
decoding error.
Example:
----
enforce(system("echo abc>deleteme") == 0);
scope(exit) remove("deleteme");
enforce(chomp(readText("deleteme")) == "abc");
----
*/
S readText(S = string)(in char[] name)
{
auto result = cast(S) read(name);
std.utf.validate(result);
return result;
}
unittest
{
write(deleteme, "abc\n");
scope(exit) { assert(exists(deleteme)); remove(deleteme); }
enforce(chomp(readText(deleteme)) == "abc");
}
/*********************************************
Write $(D buffer) to file $(D name).
Throws: $(D FileException) on error.
Example:
----
import std.file;
void main()
{
int[] a = [ 0, 1, 1, 2, 3, 5, 8 ];
write("filename", a);
assert(cast(int[]) read("filename") == a);
}
----
*/
void write(in char[] name, const void[] buffer)
{
version(Windows)
{
alias TypeTuple!(GENERIC_WRITE, 0, null, CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN,
HANDLE.init)
defaults;
auto h = useWfuncs
? CreateFileW(std.utf.toUTF16z(name), defaults)
: CreateFileA(toMBSz(name), defaults);
cenforce(h != INVALID_HANDLE_VALUE, name);
scope(exit) cenforce(CloseHandle(h), name);
DWORD numwritten;
cenforce(WriteFile(h, buffer.ptr, buffer.length, &numwritten, null) == 1
&& buffer.length == numwritten,
name);
}
else version(Posix)
return writeImpl(name, buffer, O_CREAT | O_WRONLY | O_TRUNC);
}
/*********************************************
Appends $(D buffer) to file $(D name).
Throws: $(D FileException) on error.
Example:
----
import std.file;
void main()
{
int[] a = [ 0, 1, 1, 2, 3, 5, 8 ];
write("filename", a);
int[] b = [ 13, 21 ];
append("filename", b);
assert(cast(int[]) read("filename") == a ~ b);
}
----
*/
void append(in char[] name, in void[] buffer)
{
version(Windows)
{
alias TypeTuple!(GENERIC_WRITE,0,null,OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN,HANDLE.init)
defaults;
auto h = useWfuncs
? CreateFileW(std.utf.toUTF16z(name), defaults)
: CreateFileA(toMBSz(name), defaults);
cenforce(h != INVALID_HANDLE_VALUE, name);
scope(exit) cenforce(CloseHandle(h), name);
DWORD numwritten;
cenforce(SetFilePointer(h, 0, null, FILE_END) != INVALID_SET_FILE_POINTER
&& WriteFile(h,buffer.ptr,buffer.length,&numwritten,null) == 1
&& buffer.length == numwritten,
name);
}
else version(Posix)
return writeImpl(name, buffer, O_APPEND | O_WRONLY | O_CREAT);
}
// Posix implementation helper for write and append
version(Posix) private void writeImpl(in char[] name,
in void[] buffer, in uint mode)
{
immutable fd = core.sys.posix.fcntl.open(toStringz(name),
mode, octal!666);
cenforce(fd != -1, name);
{
scope(failure) core.sys.posix.unistd.close(fd);
immutable size = buffer.length;
cenforce(
core.sys.posix.unistd.write(fd, buffer.ptr, size) == size,
name);
}
cenforce(core.sys.posix.unistd.close(fd) == 0, name);
}
/***************************************************
* Rename file $(D from) to $(D to).
* Throws: $(D FileException) on error.
*/
void rename(in char[] from, in char[] to)
{
version(Windows)
{
enforce(useWfuncs
? MoveFileW(std.utf.toUTF16z(from), std.utf.toUTF16z(to))
: MoveFileA(toMBSz(from), toMBSz(to)),
new FileException(
text("Attempting to rename file ", from, " to ",
to)));
}
else version(Posix)
cenforce(std.c.stdio.rename(toStringz(from), toStringz(to)) == 0, to);
}
/***************************************************
Delete file $(D name).
Throws: $(D FileException) on error.
*/
void remove(in char[] name)
{
version(Windows)
{
cenforce(useWfuncs
? DeleteFileW(std.utf.toUTF16z(name))
: DeleteFileA(toMBSz(name)),
name);
}
else version(Posix)
cenforce(std.c.stdio.remove(toStringz(name)) == 0,
"Failed to remove file " ~ name);
}
/***************************************************
Get size of file $(D name) in bytes.
Throws: $(D FileException) on error (e.g., file not found).
*/
ulong getSize(in char[] name)
{
version(Windows)
{
HANDLE findhndl = void;
uint resulth = void;
uint resultl = void;
const (char)[] file = name[];
//FindFirstFileX can't handle file names which end in a backslash.
if(file.endsWith(sep))
file.popBackN(sep.length);
if (useWfuncs)
{
WIN32_FIND_DATAW filefindbuf;
findhndl = FindFirstFileW(std.utf.toUTF16z(file), &filefindbuf);
resulth = filefindbuf.nFileSizeHigh;
resultl = filefindbuf.nFileSizeLow;
}
else
{
WIN32_FIND_DATA filefindbuf;
findhndl = FindFirstFileA(toMBSz(file), &filefindbuf);
resulth = filefindbuf.nFileSizeHigh;
resultl = filefindbuf.nFileSizeLow;
}
cenforce(findhndl != cast(HANDLE)-1 && FindClose(findhndl), file);
return (cast(ulong) resulth << 32) + resultl;
}
else version(Posix)
{
struct_stat64 statbuf = void;
cenforce(stat64(toStringz(name), &statbuf) == 0, name);
return statbuf.st_size;
}
}
unittest
{
// create a file of size 1
write(deleteme, "a");
scope(exit) { assert(exists(deleteme)); remove(deleteme); }
assert(getSize(deleteme) == 1);
// create a file of size 3
write(deleteme, "abc");
assert(getSize(deleteme) == 3);
}
/*************************
* $(RED Scheduled for deprecation in August 2011. Please use either the version
* of $(D getTimes) which takes two arguments or $(D getTimesWin)
* (Windows-Only) instead.)
*/
version(StdDdoc) void getTimes(in char[] name,
out d_time ftc,
out d_time fta,
out d_time ftm);
else version(Windows) void getTimes(C)(in C[] name,
out d_time ftc,
out d_time fta,
out d_time ftm) if(is(Unqual!C == char))
{
pragma(msg, "Warning: As of Phobos 2.052, std.file.getTimes with 3 arguments has been " ~
"scheduled for deprecation in August 2011. Please use " ~
"either the version of getTimes with two arguments or " ~
"getTimesWin (Windows-Only) instead.");
HANDLE findhndl = void;
if (useWfuncs)
{
WIN32_FIND_DATAW filefindbuf;
findhndl = FindFirstFileW(std.utf.toUTF16z(name), &filefindbuf);
ftc = FILETIME2d_time(&filefindbuf.ftCreationTime);
fta = FILETIME2d_time(&filefindbuf.ftLastAccessTime);
ftm = FILETIME2d_time(&filefindbuf.ftLastWriteTime);
}
else
{
WIN32_FIND_DATA filefindbuf;
findhndl = FindFirstFileA(toMBSz(name), &filefindbuf);
ftc = FILETIME2d_time(&filefindbuf.ftCreationTime);
fta = FILETIME2d_time(&filefindbuf.ftLastAccessTime);
ftm = FILETIME2d_time(&filefindbuf.ftLastWriteTime);
}
if (findhndl == cast(HANDLE)-1)
{
throw new FileException(name.idup);
}
FindClose(findhndl);
}
else version(Posix) void getTimes(C)(in C[] name,
out d_time ftc,
out d_time fta,
out d_time ftm) if(is(Unqual!C == char))
{
pragma(msg, "Warning: As of Phobos 2.052, std.file.getTimes with 3 arguments has been " ~
"scheduled for deprecation in August 2011. Please use " ~
"either the version of getTimes with two arguments or " ~
"getTimesWin (Windows-Only) instead.");
struct_stat64 statbuf = void;
cenforce(stat64(toStringz(name), &statbuf) == 0, name);
ftc = cast(d_time) statbuf.st_ctime * ticksPerSecond;
fta = cast(d_time) statbuf.st_atime * ticksPerSecond;
ftm = cast(d_time) statbuf.st_mtime * ticksPerSecond;
}
/++
Get the access and modified times of file $(D name).
Params:
name = File name to get times for.
fileAccessTime = Time the file was last accessed.
fileModificationTime = Time the file was last modified.
Throws:
$(D FileException) on error.
+/
version(StdDdoc) void getTimes(in char[] name,
out SysTime fileAccessTime,
out SysTime fileModificationTime);
//Oh, how it would be nice of you could overload templated functions with
//non-templated functions. Untemplatize this when the old getTimes goes away.
else void getTimes(C)(in C[] name,
out SysTime fileAccessTime,
out SysTime fileModificationTime)
if(is(Unqual!C == char))
{
version(Windows)
{
HANDLE findhndl = void;
if(useWfuncs)
{
WIN32_FIND_DATAW filefindbuf;
findhndl = FindFirstFileW(std.utf.toUTF16z(name), &filefindbuf);
fileAccessTime = std.datetime.FILETIMEToSysTime(&filefindbuf.ftLastAccessTime);
fileModificationTime = std.datetime.FILETIMEToSysTime(&filefindbuf.ftLastWriteTime);
}
else
{
WIN32_FIND_DATA filefindbuf;
findhndl = FindFirstFileA(toMBSz(name), &filefindbuf);
fileAccessTime = std.datetime.FILETIMEToSysTime(&filefindbuf.ftLastAccessTime);
fileModificationTime = std.datetime.FILETIMEToSysTime(&filefindbuf.ftLastWriteTime);
}
enforce(findhndl != cast(HANDLE)-1, new FileException(name.idup));
FindClose(findhndl);
}
else version(Posix)
{
struct_stat64 statbuf = void;
cenforce(stat64(toStringz(name), &statbuf) == 0, name);
fileAccessTime = SysTime(unixTimeToStdTime(statbuf.st_atime));
fileModificationTime = SysTime(unixTimeToStdTime(statbuf.st_mtime));
}
}
unittest
{
auto currTime = Clock.currTime();
write(deleteme, "a");
scope(exit) { assert(exists(deleteme)); remove(deleteme); }
SysTime accessTime1 = void;
SysTime modificationTime1 = void;
getTimes(deleteme, accessTime1, modificationTime1);
enum leeway = dur!"seconds"(4);
{
auto diffa = accessTime1 - currTime;
auto diffm = modificationTime1 - currTime;
assert(abs(diffa) <= leeway);
assert(abs(diffm) <= leeway);
}
Thread.sleep(dur!"seconds"(1));
currTime = Clock.currTime();
write(deleteme, "b");
SysTime accessTime2 = void;
SysTime modificationTime2 = void;
getTimes(deleteme, accessTime2, modificationTime2);
{
auto diffa = accessTime2 - currTime;
auto diffm = modificationTime2 - currTime;
assert(abs(diffa) <= leeway);
assert(abs(diffm) <= leeway);
}
assert(accessTime1 <= accessTime2);
assert(modificationTime1 <= modificationTime2);
}
/++
$(BLUE This function is Windows-Only.)
Get creation/access/modified times of file $(D name).
This is the same as $(D getTimes) except that it also gives you the file
creation time - which isn't possible on Posix systems.
Params:
name = File name to get times for.
fileCreationTime = Time the file was created.
fileAccessTime = Time the file was last accessed.
fileModificationTime = Time the file was last modified.
Throws:
$(D FileException) on error.
+/
version(StdDdoc) void getTimesWin(in char[] name,
out SysTime fileCreationTime,
out SysTime fileAccessTime,
out SysTime fileModificationTime);
else version(Windows) void getTimesWin(in char[] name,
out SysTime fileCreationTime,
out SysTime fileAccessTime,
out SysTime fileModificationTime)
{
HANDLE findhndl = void;
if (useWfuncs)
{
WIN32_FIND_DATAW filefindbuf;
findhndl = FindFirstFileW(std.utf.toUTF16z(name), &filefindbuf);
fileCreationTime = std.datetime.FILETIMEToSysTime(&filefindbuf.ftCreationTime);
fileAccessTime = std.datetime.FILETIMEToSysTime(&filefindbuf.ftLastAccessTime);
fileModificationTime = std.datetime.FILETIMEToSysTime(&filefindbuf.ftLastWriteTime);
}
else
{
WIN32_FIND_DATA filefindbuf;
findhndl = FindFirstFileA(toMBSz(name), &filefindbuf);
fileCreationTime = std.datetime.FILETIMEToSysTime(&filefindbuf.ftCreationTime);
fileAccessTime = std.datetime.FILETIMEToSysTime(&filefindbuf.ftLastAccessTime);
fileModificationTime = std.datetime.FILETIMEToSysTime(&filefindbuf.ftLastWriteTime);
}
if(findhndl == cast(HANDLE)-1)
{
throw new FileException(name.idup);
}
FindClose(findhndl);
}
version(Windows) unittest
{
auto currTime = Clock.currTime();
write(deleteme, "a");
scope(exit) { assert(exists(deleteme)); remove(deleteme); }
SysTime creationTime1 = void;
SysTime accessTime1 = void;
SysTime modificationTime1 = void;
getTimesWin(deleteme, creationTime1, accessTime1, modificationTime1);
enum leeway = dur!"seconds"(4);
{
auto diffc = creationTime1 - currTime;
auto diffa = accessTime1 - currTime;
auto diffm = modificationTime1 - currTime;
assert(abs(diffc) <= leeway);
assert(abs(diffa) <= leeway);
assert(abs(diffm) <= leeway);
}
Thread.sleep(dur!"seconds"(1));
currTime = Clock.currTime();
write(deleteme, "b");
SysTime creationTime2 = void;
SysTime accessTime2 = void;
SysTime modificationTime2 = void;
getTimesWin(deleteme, creationTime2, accessTime2, modificationTime2);
{
auto diffa = accessTime2 - currTime;
auto diffm = modificationTime2 - currTime;
assert(abs(diffa) <= leeway);
assert(abs(diffm) <= leeway);
}
assert(creationTime1 <= creationTime2);
assert(accessTime1 <= accessTime2);
assert(modificationTime1 <= modificationTime2);
}
/++
$(RED Scheduled for deprecation in October 2011. Please use the
$(D getTimes) with two arguments instead.)
$(BLUE This function is Posix-Only.)
Get file status change time, acces time, and modification times
of file $(D name).
$(D getTimes) is the same on both Windows and Posix, but it is not
possible to get the file creation time on Posix systems, so
$(D getTimes) cannot give you the file creation time. $(D getTimesWin)
does the same thing on Windows as $(D getTimes) except that it also gives
you the file creation time. This function was created to do the same
thing that the old, 3 argument $(D getTimes) was doing on Posix - giving
you the time that the file status last changed - but ultimately, that's
not really very useful, and we don't like having functions which are
OS-specific when we can reasonably avoid it. So, this function is being
deprecated. You can use $(D DirEntry)'s $(D statBuf) property if you
really want to get at that information (along with all of the other
OS-specific stuff that $(D stat) gives you).
Params:
name = File name to get times for.
fileStatusChangeTime = Time the file's status was last changed.
fileAccessTime = Time the file was last accessed.
fileModificationTime = Time the file was last modified.
Throws:
$(D FileException) on error.
+/
version(StdDdoc) void getTimesPosix(in char[] name,
out SysTime fileStatusChangeTime,
out SysTime fileAccessTime,
out SysTime fileModificationTime);
else version(Posix) void getTimesPosix(C)(in C[] name,
out SysTime fileStatusChangeTime,
out SysTime fileAccessTime,
out SysTime fileModificationTime)
if(is(Unqual!C == char))
{
pragma(msg, "Warning: As of Phobos 2.054, std.file.getTimesPosix has been " ~
"scheduled for deprecation in October 2011. Please use " ~
"the version of getTimes with two arguments instead.");
struct_stat64 statbuf = void;
cenforce(stat64(toStringz(name), &statbuf) == 0, name);
fileStatusChangeTime = SysTime(unixTimeToStdTime(statbuf.st_ctime));
fileAccessTime = SysTime(unixTimeToStdTime(statbuf.st_atime));
fileModificationTime = SysTime(unixTimeToStdTime(statbuf.st_mtime));
}
/++
$(RED Scheduled for deprecation in August 2011. Please use
$(D timeLastModified) instead.)
+/
version(StdDdoc) d_time lastModified(in char[] name);
else d_time lastModified(C)(in C[] name)
if(is(Unqual!C == char))
{
pragma(msg, softDeprec!("2.052", "August 2011", "lastModified", "timeLastModified"));
version(Windows)
{
d_time dummy = void, ftm = void;
getTimes(name, dummy, dummy, ftm);
return ftm;
}
else version(Posix)
{
struct_stat64 statbuf = void;
cenforce(stat64(toStringz(name), &statbuf) == 0, name);
return cast(d_time) statbuf.st_mtime * ticksPerSecond;
}
}
/++
$(RED Scheduled for deprecation in August 2011.
Please use $(D timeLastModified) instead.)
+/
version(StdDdoc) d_time lastModified(in char[] name, d_time returnIfMissing);
else d_time lastModified(C)(in C[] name, d_time returnIfMissing)
if(is(Unqual!C == char))
{
pragma(msg, softDeprec!("2.052", "August 2011", "lastModified", "timeLastModified"));
version(Windows)
{
if (!exists(name)) return returnIfMissing;
d_time dummy = void, ftm = void;
getTimes(name, dummy, dummy, ftm);
return ftm;
}
else version(Posix)
{
struct_stat64 statbuf = void;
return stat64(toStringz(name), &statbuf) != 0
? returnIfMissing
: cast(d_time) statbuf.st_mtime * ticksPerSecond;
}
}
unittest
{
//std.process.system("echo a>deleteme") == 0 || assert(false);
if (exists(deleteme)) remove(deleteme);
write(deleteme, "a\n");
scope(exit) { assert(exists(deleteme)); remove(deleteme); }
// assert(lastModified("deleteme") >
// lastModified("this file does not exist", d_time.min));
//assert(lastModified("deleteme") > lastModified(__FILE__));
}
/++
Returns the time that the given file was last modified.