forked from dlang/phobos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstdio.d
5463 lines (4789 loc) · 150 KB
/
stdio.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.
/**
Standard I/O functions that extend $(B core.stdc.stdio). $(B core.stdc.stdio)
is $(D_PARAM public)ally imported when importing $(B std.stdio).
Source: $(PHOBOSSRC std/stdio.d)
Copyright: Copyright Digital Mars 2007-.
License: $(HTTP boost.org/LICENSE_1_0.txt, Boost License 1.0).
Authors: $(HTTP digitalmars.com, Walter Bright),
$(HTTP erdani.org, Andrei Alexandrescu),
Alex Rønne Petersen
*/
module std.stdio;
import core.stdc.stddef; // wchar_t
public import core.stdc.stdio;
import std.algorithm.mutation; // copy
import std.meta; // allSatisfy
import std.range.primitives; // ElementEncodingType, empty, front,
// isBidirectionalRange, isInputRange, put
import std.traits; // isSomeChar, isSomeString, Unqual, isPointer
import std.typecons; // Flag
/++
If flag `KeepTerminator` is set to `KeepTerminator.yes`, then the delimiter
is included in the strings returned.
+/
alias KeepTerminator = Flag!"keepTerminator";
version (CRuntime_Microsoft)
{
version = MICROSOFT_STDIO;
}
else version (CRuntime_DigitalMars)
{
// Specific to the way Digital Mars C does stdio
version = DIGITAL_MARS_STDIO;
}
version (CRuntime_Glibc)
{
// Specific to the way Gnu C does stdio
version = GCC_IO;
version = HAS_GETDELIM;
}
else version (CRuntime_Bionic)
{
version = GENERIC_IO;
version = HAS_GETDELIM;
}
else version (CRuntime_Musl)
{
version = GENERIC_IO;
version = HAS_GETDELIM;
}
else version (CRuntime_UClibc)
{
// uClibc supports GCC IO
version = GCC_IO;
version = HAS_GETDELIM;
}
version (OSX)
{
version = GENERIC_IO;
version = HAS_GETDELIM;
}
else version (FreeBSD)
{
version = GENERIC_IO;
version = HAS_GETDELIM;
}
else version (NetBSD)
{
version = GENERIC_IO;
version = HAS_GETDELIM;
}
else version (DragonFlyBSD)
{
version = GENERIC_IO;
version = HAS_GETDELIM;
}
else version (Solaris)
{
version = GENERIC_IO;
version = NO_GETDELIM;
}
// Character type used for operating system filesystem APIs
version (Windows)
{
private alias FSChar = wchar;
}
else version (Posix)
{
private alias FSChar = char;
}
else
static assert(0);
version(Windows)
{
// core.stdc.stdio.fopen expects file names to be
// encoded in CP_ACP on Windows instead of UTF-8.
/+ Waiting for druntime pull 299
+/
extern (C) nothrow @nogc FILE* _wfopen(in wchar* filename, in wchar* mode);
extern (C) nothrow @nogc FILE* _wfreopen(in wchar* filename, in wchar* mode, FILE* fp);
import core.sys.windows.windows : HANDLE;
}
version (DIGITAL_MARS_STDIO)
{
extern (C)
{
/* **
* Digital Mars under-the-hood C I/O functions.
* Use _iobuf* for the unshared version of FILE*,
* usable when the FILE is locked.
*/
nothrow:
@nogc:
int _fputc_nlock(int, _iobuf*);
int _fputwc_nlock(int, _iobuf*);
int _fgetc_nlock(_iobuf*);
int _fgetwc_nlock(_iobuf*);
int __fp_lock(FILE*);
void __fp_unlock(FILE*);
int setmode(int, int);
}
alias FPUTC = _fputc_nlock;
alias FPUTWC = _fputwc_nlock;
alias FGETC = _fgetc_nlock;
alias FGETWC = _fgetwc_nlock;
alias FLOCK = __fp_lock;
alias FUNLOCK = __fp_unlock;
alias _setmode = setmode;
enum _O_BINARY = 0x8000;
int _fileno(FILE* f) { return f._file; }
alias fileno = _fileno;
}
else version (MICROSOFT_STDIO)
{
extern (C)
{
/* **
* Microsoft under-the-hood C I/O functions
*/
nothrow:
@nogc:
int _fputc_nolock(int, _iobuf*);
int _fputwc_nolock(int, _iobuf*);
int _fgetc_nolock(_iobuf*);
int _fgetwc_nolock(_iobuf*);
void _lock_file(FILE*);
void _unlock_file(FILE*);
int _setmode(int, int);
int _fileno(FILE*);
FILE* _fdopen(int, const (char)*);
int _fseeki64(FILE*, long, int);
long _ftelli64(FILE*);
}
alias FPUTC = _fputc_nolock;
alias FPUTWC = _fputwc_nolock;
alias FGETC = _fgetc_nolock;
alias FGETWC = _fgetwc_nolock;
alias FLOCK = _lock_file;
alias FUNLOCK = _unlock_file;
alias setmode = _setmode;
alias fileno = _fileno;
enum
{
_O_RDONLY = 0x0000,
_O_APPEND = 0x0004,
_O_TEXT = 0x4000,
_O_BINARY = 0x8000,
}
}
else version (GCC_IO)
{
/* **
* Gnu under-the-hood C I/O functions; see
* http://gnu.org/software/libc/manual/html_node/I_002fO-on-Streams.html
*/
extern (C)
{
nothrow:
@nogc:
int fputc_unlocked(int, _iobuf*);
int fputwc_unlocked(wchar_t, _iobuf*);
int fgetc_unlocked(_iobuf*);
int fgetwc_unlocked(_iobuf*);
void flockfile(FILE*);
void funlockfile(FILE*);
private size_t fwrite_unlocked(const(void)* ptr,
size_t size, size_t n, _iobuf *stream);
}
alias FPUTC = fputc_unlocked;
alias FPUTWC = fputwc_unlocked;
alias FGETC = fgetc_unlocked;
alias FGETWC = fgetwc_unlocked;
alias FLOCK = flockfile;
alias FUNLOCK = funlockfile;
}
else version (GENERIC_IO)
{
nothrow:
@nogc:
extern (C)
{
void flockfile(FILE*);
void funlockfile(FILE*);
}
int fputc_unlocked(int c, _iobuf* fp) { return fputc(c, cast(shared) fp); }
int fputwc_unlocked(wchar_t c, _iobuf* fp)
{
import core.stdc.wchar_ : fputwc;
return fputwc(c, cast(shared) fp);
}
int fgetc_unlocked(_iobuf* fp) { return fgetc(cast(shared) fp); }
int fgetwc_unlocked(_iobuf* fp)
{
import core.stdc.wchar_ : fgetwc;
return fgetwc(cast(shared) fp);
}
alias FPUTC = fputc_unlocked;
alias FPUTWC = fputwc_unlocked;
alias FGETC = fgetc_unlocked;
alias FGETWC = fgetwc_unlocked;
alias FLOCK = flockfile;
alias FUNLOCK = funlockfile;
}
else
{
static assert(0, "unsupported C I/O system");
}
version(HAS_GETDELIM) extern(C) nothrow @nogc
{
ptrdiff_t getdelim(char**, size_t*, int, FILE*);
// getline() always comes together with getdelim()
ptrdiff_t getline(char**, size_t*, FILE*);
}
//------------------------------------------------------------------------------
private struct ByRecordImpl(Fields...)
{
private:
import std.typecons : Tuple;
File file;
char[] line;
Tuple!(Fields) current;
string format;
public:
this(File f, string format)
{
assert(f.isOpen);
file = f;
this.format = format;
popFront(); // prime the range
}
/// Range primitive implementations.
@property bool empty()
{
return !file.isOpen;
}
/// Ditto
@property ref Tuple!(Fields) front()
{
return current;
}
/// Ditto
void popFront()
{
import std.conv : text;
import std.exception : enforce;
import std.format : formattedRead;
import std.string : chomp;
enforce(file.isOpen, "ByRecord: File must be open");
file.readln(line);
if (!line.length)
{
file.detach();
}
else
{
line = chomp(line);
formattedRead(line, format, ¤t);
enforce(line.empty, text("Leftover characters in record: `",
line, "'"));
}
}
}
// @@@DEPRECATED_2019-01@@@
deprecated("Use .byRecord")
struct ByRecord(Fields...)
{
ByRecordImpl!Fields payload;
alias payload this;
}
template byRecord(Fields...)
{
auto byRecord(File f, string format)
{
return typeof(return)(f, format);
}
}
/**
Encapsulates a `FILE*`. Generally D does not attempt to provide
thin wrappers over equivalent functions in the C standard library, but
manipulating `FILE*` values directly is unsafe and error-prone in
many ways. The `File` type ensures safe manipulation, automatic
file closing, and a lot of convenience.
The underlying `FILE*` handle is maintained in a reference-counted
manner, such that as soon as the last `File` variable bound to a
given `FILE*` goes out of scope, the underlying `FILE*` is
automatically closed.
Example:
----
// test.d
void main(string[] args)
{
auto f = File("test.txt", "w"); // open for writing
f.write("Hello");
if (args.length > 1)
{
auto g = f; // now g and f write to the same file
// internal reference count is 2
g.write(", ", args[1]);
// g exits scope, reference count decreases to 1
}
f.writeln("!");
// f exits scope, reference count falls to zero,
// underlying `FILE*` is closed.
}
----
$(CONSOLE
% rdmd test.d Jimmy
% cat test.txt
Hello, Jimmy!
% __
)
*/
struct File
{
import core.atomic : atomicOp, atomicStore, atomicLoad;
import std.range.primitives : ElementEncodingType;
import std.traits : isScalarType, isArray;
enum Orientation { unknown, narrow, wide }
private struct Impl
{
FILE * handle = null; // Is null iff this Impl is closed by another File
shared uint refs = uint.max / 2;
bool isPopened; // true iff the stream has been created by popen()
Orientation orientation;
}
private Impl* _p;
private string _name;
package this(FILE* handle, string name, uint refs = 1, bool isPopened = false) @trusted
{
import core.stdc.stdlib : malloc;
import std.exception : enforce;
assert(!_p);
_p = cast(Impl*) enforce(malloc(Impl.sizeof), "Out of memory");
initImpl(handle, name, refs, isPopened);
}
private void initImpl(FILE* handle, string name, uint refs = 1, bool isPopened = false)
{
assert(_p);
_p.handle = handle;
atomicStore(_p.refs, refs);
_p.isPopened = isPopened;
_p.orientation = Orientation.unknown;
_name = name;
}
/**
Constructor taking the name of the file to open and the open mode.
Copying one `File` object to another results in the two `File`
objects referring to the same underlying file.
The destructor automatically closes the file as soon as no `File`
object refers to it anymore.
Params:
name = range or string representing the file _name
stdioOpenmode = range or string represting the open mode
(with the same semantics as in the C standard library
$(HTTP cplusplus.com/reference/clibrary/cstdio/fopen.html, fopen)
function)
Throws: `ErrnoException` if the file could not be opened.
*/
this(string name, scope const(char)[] stdioOpenmode = "rb") @safe
{
import std.conv : text;
import std.exception : errnoEnforce;
this(errnoEnforce(.fopen(name, stdioOpenmode),
text("Cannot open file `", name, "' in mode `",
stdioOpenmode, "'")),
name);
// MSVCRT workaround (issue 14422)
version (MICROSOFT_STDIO)
{
setAppendWin(stdioOpenmode);
}
}
/// ditto
this(R1, R2)(R1 name)
if (isInputRange!R1 && isSomeChar!(ElementEncodingType!R1))
{
import std.conv : to;
this(name.to!string, "rb");
}
/// ditto
this(R1, R2)(R1 name, R2 mode)
if (isInputRange!R1 && isSomeChar!(ElementEncodingType!R1) &&
isInputRange!R2 && isSomeChar!(ElementEncodingType!R2))
{
import std.conv : to;
this(name.to!string, mode.to!string);
}
@safe unittest
{
static import std.file;
import std.utf : byChar;
auto deleteme = testFilename();
auto f = File(deleteme.byChar, "w".byChar);
f.close();
std.file.remove(deleteme);
}
~this() @safe
{
detach();
}
this(this) @safe nothrow
{
if (!_p) return;
assert(atomicLoad(_p.refs));
atomicOp!"+="(_p.refs, 1);
}
/**
Assigns a file to another. The target of the assignment gets detached
from whatever file it was attached to, and attaches itself to the new
file.
*/
void opAssign(File rhs) @safe
{
import std.algorithm.mutation : swap;
swap(this, rhs);
}
/**
Detaches from the current file (throwing on failure), and then attempts to
_open file `name` with mode `stdioOpenmode`. The mode has the
same semantics as in the C standard library $(HTTP
cplusplus.com/reference/clibrary/cstdio/fopen.html, fopen) function.
Throws: `ErrnoException` in case of error.
*/
void open(string name, scope const(char)[] stdioOpenmode = "rb") @trusted
{
resetFile(name, stdioOpenmode, false);
}
private void resetFile(string name, scope const(char)[] stdioOpenmode, bool isPopened) @trusted
{
import core.stdc.stdlib : malloc;
import std.exception : enforce;
import std.conv : text;
import std.exception : errnoEnforce;
if (_p !is null)
{
detach();
}
_p = cast(Impl*) enforce(malloc(Impl.sizeof), "Out of memory");
FILE* handle;
version (Posix)
{
if (isPopened)
{
errnoEnforce(handle = .popen(name, stdioOpenmode),
"Cannot run command `"~name~"'");
}
else
{
errnoEnforce(handle = .fopen(name, stdioOpenmode),
text("Cannot open file `", name, "' in mode `",
stdioOpenmode, "'"));
}
}
else
{
assert(isPopened == false);
errnoEnforce(handle = .fopen(name, stdioOpenmode),
text("Cannot open file `", name, "' in mode `",
stdioOpenmode, "'"));
}
initImpl(handle, name, 1, isPopened);
version (MICROSOFT_STDIO)
{
setAppendWin(stdioOpenmode);
}
}
private void closeHandles() @trusted
{
assert(_p);
import std.exception : errnoEnforce;
version (Posix)
{
import core.sys.posix.stdio : pclose;
import std.format : format;
if (_p.isPopened)
{
auto res = pclose(_p.handle);
errnoEnforce(res != -1,
"Could not close pipe `"~_name~"'");
_p.handle = null;
return;
}
}
if (_p.handle)
{
errnoEnforce(.fclose(_p.handle) == 0,
"Could not close file `"~_name~"'");
_p.handle = null;
}
}
version (MICROSOFT_STDIO)
{
private void setAppendWin(scope const(char)[] stdioOpenmode) @safe
{
bool append, update;
foreach (c; stdioOpenmode)
if (c == 'a')
append = true;
else
if (c == '+')
update = true;
if (append && !update)
seek(size);
}
}
/**
Reuses the `File` object to either open a different file, or change
the file mode. If `name` is `null`, the mode of the currently open
file is changed; otherwise, a new file is opened, reusing the C
`FILE*`. The function has the same semantics as in the C standard
library $(HTTP cplusplus.com/reference/cstdio/freopen/, freopen)
function.
Note: Calling `reopen` with a `null` `name` is not implemented
in all C runtimes.
Throws: `ErrnoException` in case of error.
*/
void reopen(string name, scope const(char)[] stdioOpenmode = "rb") @trusted
{
import std.conv : text;
import std.exception : enforce, errnoEnforce;
import std.internal.cstring : tempCString;
enforce(isOpen, "Attempting to reopen() an unopened file");
auto namez = (name == null ? _name : name).tempCString!FSChar();
auto modez = stdioOpenmode.tempCString!FSChar();
FILE* fd = _p.handle;
version (Windows)
fd = _wfreopen(namez, modez, fd);
else
fd = freopen(namez, modez, fd);
errnoEnforce(fd, name
? text("Cannot reopen file `", name, "' in mode `", stdioOpenmode, "'")
: text("Cannot reopen file in mode `", stdioOpenmode, "'"));
if (name !is null)
_name = name;
}
@system unittest // Test changing filename
{
import std.exception : assertThrown, assertNotThrown;
static import std.file;
auto deleteme = testFilename();
std.file.write(deleteme, "foo");
scope(exit) std.file.remove(deleteme);
auto f = File(deleteme);
assert(f.readln() == "foo");
auto deleteme2 = testFilename();
std.file.write(deleteme2, "bar");
scope(exit) std.file.remove(deleteme2);
f.reopen(deleteme2);
assert(f.name == deleteme2);
assert(f.readln() == "bar");
f.close();
}
version (CRuntime_DigitalMars) {} else // Not implemented
version (CRuntime_Microsoft) {} else // Not implemented
@system unittest // Test changing mode
{
import std.exception : assertThrown, assertNotThrown;
static import std.file;
auto deleteme = testFilename();
std.file.write(deleteme, "foo");
scope(exit) std.file.remove(deleteme);
auto f = File(deleteme, "r+");
assert(f.readln() == "foo");
f.reopen(null, "w");
f.write("bar");
f.seek(0);
f.reopen(null, "a");
f.write("baz");
assert(f.name == deleteme);
f.close();
assert(std.file.readText(deleteme) == "barbaz");
}
/**
Detaches from the current file (throwing on failure), and then runs a command
by calling the C standard library function $(HTTP
opengroup.org/onlinepubs/007908799/xsh/_popen.html, _popen).
Throws: `ErrnoException` in case of error.
*/
version(Posix) void popen(string command, scope const(char)[] stdioOpenmode = "r") @safe
{
resetFile(command, stdioOpenmode ,true);
}
/**
First calls `detach` (throwing on failure), and then attempts to
associate the given file descriptor with the `File`. The mode must
be compatible with the mode of the file descriptor.
Throws: `ErrnoException` in case of error.
*/
void fdopen(int fd, scope const(char)[] stdioOpenmode = "rb") @safe
{
fdopen(fd, stdioOpenmode, null);
}
package void fdopen(int fd, scope const(char)[] stdioOpenmode, string name) @trusted
{
import std.exception : errnoEnforce;
import std.internal.cstring : tempCString;
auto modez = stdioOpenmode.tempCString();
detach();
version (DIGITAL_MARS_STDIO)
{
// This is a re-implementation of DMC's fdopen, but without the
// mucking with the file descriptor. POSIX standard requires the
// new fdopen'd file to retain the given file descriptor's
// position.
import core.stdc.stdio : fopen;
auto fp = fopen("NUL", modez);
errnoEnforce(fp, "Cannot open placeholder NUL stream");
FLOCK(fp);
auto iob = cast(_iobuf*) fp;
.close(iob._file);
iob._file = fd;
iob._flag &= ~_IOTRAN;
FUNLOCK(fp);
}
else
{
version (Windows) // MSVCRT
auto fp = _fdopen(fd, modez);
else version (Posix)
{
import core.sys.posix.stdio : fdopen;
auto fp = fdopen(fd, modez);
}
errnoEnforce(fp);
}
this = File(fp, name);
}
// Declare a dummy HANDLE to allow generating documentation
// for Windows-only methods.
version(StdDdoc) { version(Windows) {} else alias HANDLE = int; }
/**
First calls `detach` (throwing on failure), and then attempts to
associate the given Windows `HANDLE` with the `File`. The mode must
be compatible with the access attributes of the handle. Windows only.
Throws: `ErrnoException` in case of error.
*/
version(StdDdoc)
void windowsHandleOpen(HANDLE handle, scope const(char)[] stdioOpenmode);
version(Windows)
void windowsHandleOpen(HANDLE handle, scope const(char)[] stdioOpenmode)
{
import core.stdc.stdint : intptr_t;
import std.exception : errnoEnforce;
import std.format : format;
// Create file descriptors from the handles
version (DIGITAL_MARS_STDIO)
auto fd = _handleToFD(handle, FHND_DEVICE);
else // MSVCRT
{
int mode;
modeLoop:
foreach (c; stdioOpenmode)
switch (c)
{
case 'r': mode |= _O_RDONLY; break;
case '+': mode &=~_O_RDONLY; break;
case 'a': mode |= _O_APPEND; break;
case 'b': mode |= _O_BINARY; break;
case 't': mode |= _O_TEXT; break;
case ',': break modeLoop;
default: break;
}
auto fd = _open_osfhandle(cast(intptr_t) handle, mode);
}
errnoEnforce(fd >= 0, "Cannot open Windows HANDLE");
fdopen(fd, stdioOpenmode, "HANDLE(%s)".format(handle));
}
/** Returns `true` if the file is opened. */
@property bool isOpen() const @safe pure nothrow
{
return _p !is null && _p.handle;
}
/**
Returns `true` if the file is at end (see $(HTTP
cplusplus.com/reference/clibrary/cstdio/feof.html, feof)).
Throws: `Exception` if the file is not opened.
*/
@property bool eof() const @trusted pure
{
import std.exception : enforce;
enforce(_p && _p.handle, "Calling eof() against an unopened file.");
return .feof(cast(FILE*) _p.handle) != 0;
}
/** Returns the name of the last opened file, if any.
If a `File` was created with $(LREF tmpfile) and $(LREF wrapFile)
it has no name.*/
@property string name() const @safe pure nothrow
{
return _name;
}
/**
If the file is not opened, returns `true`. Otherwise, returns
$(HTTP cplusplus.com/reference/clibrary/cstdio/ferror.html, ferror) for
the file handle.
*/
@property bool error() const @trusted pure nothrow
{
return !isOpen || .ferror(cast(FILE*) _p.handle);
}
@safe unittest
{
// Issue 12349
static import std.file;
auto deleteme = testFilename();
auto f = File(deleteme, "w");
scope(exit) std.file.remove(deleteme);
f.close();
assert(f.error);
}
/**
Detaches from the underlying file. If the sole owner, calls `close`.
Throws: `ErrnoException` on failure if closing the file.
*/
void detach() @trusted
{
import core.stdc.stdlib : free;
if (!_p) return;
scope(exit) _p = null;
if (atomicOp!"-="(_p.refs, 1) == 0)
{
scope(exit) free(_p);
closeHandles();
}
}
@safe unittest
{
static import std.file;
auto deleteme = testFilename();
scope(exit) std.file.remove(deleteme);
auto f = File(deleteme, "w");
{
auto f2 = f;
f2.detach();
}
assert(f._p.refs == 1);
f.close();
}
/**
If the file was unopened, succeeds vacuously. Otherwise closes the
file (by calling $(HTTP
cplusplus.com/reference/clibrary/cstdio/fclose.html, fclose)),
throwing on error. Even if an exception is thrown, afterwards the $(D
File) object is empty. This is different from `detach` in that it
always closes the file; consequently, all other `File` objects
referring to the same handle will see a closed file henceforth.
Throws: `ErrnoException` on error.
*/
void close() @trusted
{
import core.stdc.stdlib : free;
import std.exception : errnoEnforce;
if (!_p) return; // succeed vacuously
scope(exit)
{
if (atomicOp!"-="(_p.refs, 1) == 0)
free(_p);
_p = null; // start a new life
}
if (!_p.handle) return; // Impl is closed by another File
scope(exit) _p.handle = null; // nullify the handle anyway
closeHandles();
}
/**
If the file is not opened, succeeds vacuously. Otherwise, returns
$(HTTP cplusplus.com/reference/clibrary/cstdio/_clearerr.html,
_clearerr) for the file handle.
*/
void clearerr() @safe pure nothrow
{
_p is null || _p.handle is null ||
.clearerr(_p.handle);
}
/**
Flushes the C `FILE` buffers.
Calls $(HTTP cplusplus.com/reference/clibrary/cstdio/_fflush.html, _fflush)
for the file handle.
Throws: `Exception` if the file is not opened or if the call to `fflush` fails.
*/
void flush() @trusted
{
import std.exception : enforce, errnoEnforce;
enforce(isOpen, "Attempting to flush() in an unopened file");
errnoEnforce(.fflush(_p.handle) == 0);
}
@safe unittest
{
// Issue 12349
import std.exception : assertThrown;
static import std.file;
auto deleteme = testFilename();
auto f = File(deleteme, "w");
scope(exit) std.file.remove(deleteme);
f.close();
assertThrown(f.flush());
}
/**
Forces any data buffered by the OS to be written to disk.
Call $(LREF flush) before calling this function to flush the C `FILE` buffers first.
This function calls
$(HTTP msdn.microsoft.com/en-us/library/windows/desktop/aa364439%28v=vs.85%29.aspx,
`FlushFileBuffers`) on Windows and
$(HTTP pubs.opengroup.org/onlinepubs/7908799/xsh/fsync.html,
`fsync`) on POSIX for the file handle.
Throws: `Exception` if the file is not opened or if the OS call fails.
*/
void sync() @trusted
{
import std.exception : enforce;
enforce(isOpen, "Attempting to sync() an unopened file");
version (Windows)
{
import core.sys.windows.windows : FlushFileBuffers;
wenforce(FlushFileBuffers(windowsHandle), "FlushFileBuffers failed");
}
else
{
import core.sys.posix.unistd : fsync;
import std.exception : errnoEnforce;
errnoEnforce(fsync(fileno) == 0, "fsync failed");
}
}
/**
Calls $(HTTP cplusplus.com/reference/clibrary/cstdio/fread.html, fread) for the
file handle. The number of items to read and the size of
each item is inferred from the size and type of the input array, respectively.
Returns: The slice of `buffer` containing the data that was actually read.
This will be shorter than `buffer` if EOF was reached before the buffer
could be filled.
Throws: `Exception` if `buffer` is empty.
`ErrnoException` if the file is not opened or the call to `fread` fails.
`rawRead` always reads in binary mode on Windows.
*/
T[] rawRead(T)(T[] buffer)
{
import std.exception : errnoEnforce;
if (!buffer.length)
throw new Exception("rawRead must take a non-empty buffer");
version(Windows)
{
immutable fd = ._fileno(_p.handle);
immutable mode = ._setmode(fd, _O_BINARY);
scope(exit) ._setmode(fd, mode);
version(DIGITAL_MARS_STDIO)
{
import core.atomic : atomicOp;
// @@@BUG@@@ 4243
immutable info = __fhnd_info[fd];
atomicOp!"&="(__fhnd_info[fd], ~FHND_TEXT);
scope(exit) __fhnd_info[fd] = info;
}
}