-
-
Notifications
You must be signed in to change notification settings - Fork 732
/
Copy pathstdio.d
6019 lines (5286 loc) · 172 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.
/**
$(SCRIPT inhibitQuickIndex = 1;)
$(DIVC quickindex,
$(BOOKTABLE,
$(TR $(TH Category) $(TH Symbols))
$(TR $(TD File handles) $(TD
$(MYREF __popen)
$(MYREF File)
$(MYREF isFileHandle)
$(MYREF openNetwork)
$(MYREF stderr)
$(MYREF stdin)
$(MYREF stdout)
))
$(TR $(TD Reading) $(TD
$(MYREF chunks)
$(MYREF lines)
$(MYREF readf)
$(MYREF readln)
))
$(TR $(TD Writing) $(TD
$(MYREF toFile)
$(MYREF write)
$(MYREF writef)
$(MYREF writefln)
$(MYREF writeln)
))
$(TR $(TD Misc) $(TD
$(MYREF KeepTerminator)
$(MYREF LockType)
$(MYREF StdioException)
))
))
Standard I/O functions that extend $(LINK2 https://dlang.org/phobos/core_stdc_stdio.html, core.stdc.stdio). $(B core.stdc.stdio)
is $(D_PARAM public)ally imported when importing $(B std.stdio).
There are three layers of I/O:
$(OL
$(LI The lowest layer is the operating system layer. The two main schemes are Windows and Posix.)
$(LI C's $(TT stdio.h) which unifies the two operating system schemes.)
$(LI $(TT std.stdio), this module, unifies the various $(TT stdio.h) implementations into
a high level package for D programs.)
)
Source: $(PHOBOSSRC std/stdio.d)
Copyright: Copyright The D Language Foundation 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
Macros:
CSTDIO=$(HTTP cplusplus.com/reference/cstdio/$1/, $1)
*/
module std.stdio;
/*
# Glossary
The three layers have many terms for their data structures and types.
Here we try to bring some sanity to them for the intrepid code spelunker.
## Windows
Handle
A Windows handle is an opaque object of type HANDLE.
The `HANDLE` for standard devices can be retrieved with
Windows `GetStdHandle()`.
## Posix
file descriptor, aka fileno, aka fildes
An int from 0..`FOPEN_MAX`, which is an index into some internal data
structure.
0 is for `stdin`, 1 for `stdout`, 2 for `stderr`.
Negative values usually indicate an error.
## stdio.h
`FILE`
A struct that encapsulates the C library's view of the operating system
files. A `FILE` should only be referred to via a pointer.
`fileno`
A field of `FILE` which is the Posix file descriptor for Posix systems, and
and an index into an array of file `HANDLE`s for Windows.
This array is how Posix behavior is emulated on Windows.
For Digital Mars C, that array is `__osfhnd[]`, and is initialized
at program start by the C runtime library.
In this module, they are typed as `fileno_t`.
`stdin`, `stdout`, `stderr`
Global pointers to `FILE` representing standard input, output, and error streams.
Being global means there are synchronization issues when multiple threads
are doing I/O on the same streams.
## 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 : ElementEncodingType, empty, front, isBidirectionalRange,
isInputRange, isSomeFiniteCharInputRange, put;
import std.traits : isSomeChar, isSomeString, Unqual;
import std.typecons : Flag, No, Yes;
/++
If flag `KeepTerminator` is set to `KeepTerminator.yes`, then the delimiter
is included in the strings returned.
+/
alias KeepTerminator = Flag!"keepTerminator";
version (CRuntime_Microsoft)
{
}
else version (CRuntime_DigitalMars)
{
}
else version (CRuntime_Glibc)
{
}
else version (CRuntime_Bionic)
{
version = GENERIC_IO;
}
else version (CRuntime_Musl)
{
version = GENERIC_IO;
}
else version (CRuntime_UClibc)
{
version = GENERIC_IO;
}
else version (OSX)
{
version = GENERIC_IO;
version = Darwin;
}
else version (iOS)
{
version = GENERIC_IO;
version = Darwin;
}
else version (TVOS)
{
version = GENERIC_IO;
version = Darwin;
}
else version (WatchOS)
{
version = GENERIC_IO;
version = Darwin;
}
else version (FreeBSD)
{
version = GENERIC_IO;
}
else version (NetBSD)
{
version = GENERIC_IO;
}
else version (OpenBSD)
{
version = GENERIC_IO;
}
else version (DragonFlyBSD)
{
version = GENERIC_IO;
}
else version (Solaris)
{
version = GENERIC_IO;
}
else
{
static assert(0, "unsupported operating system");
}
// Character type used for operating system filesystem APIs
version (Windows)
{
private alias FSChar = wchar;
}
else
{
private alias FSChar = char;
}
private alias fileno_t = int; // file descriptor, fildes, fileno
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(scope const wchar* filename, scope const wchar* mode);
extern (C) nothrow @nogc FILE* _wfreopen(scope const wchar* filename, scope const wchar* mode, FILE* fp);
import core.sys.windows.basetsd : HANDLE;
}
version (Posix)
{
static import core.sys.posix.stdio; // getdelim, flockfile
}
version (CRuntime_DigitalMars)
{
private alias _FPUTC = _fputc_nlock;
private alias _FPUTWC = _fputwc_nlock;
private alias _FGETC = _fgetc_nlock;
private alias _FGETWC = _fgetwc_nlock;
private alias _FLOCK = __fp_lock;
private alias _FUNLOCK = __fp_unlock;
// Alias for CRuntime_Microsoft compatibility.
// @@@DEPRECATED_2.107@@@
// Rename this back to _setmode once the deprecation phase has ended.
private alias __setmode = setmode;
// @@@DEPRECATED_2.107@@@
deprecated("internal alias FPUTC was unintentionally available from "
~ "std.stdio and will be removed afer 2.107")
alias FPUTC = _fputc_nlock;
// @@@DEPRECATED_2.107@@@
deprecated("internal alias FPUTWC was unintentionally available from "
~ "std.stdio and will be removed afer 2.107")
alias FPUTWC = _fputwc_nlock;
// @@@DEPRECATED_2.107@@@
deprecated("internal alias FGETC was unintentionally available from "
~ "std.stdio and will be removed afer 2.107")
alias FGETC = _fgetc_nlock;
// @@@DEPRECATED_2.107@@@
deprecated("internal alias FGETWC was unintentionally available from "
~ "std.stdio and will be removed afer 2.107")
alias FGETWC = _fgetwc_nlock;
// @@@DEPRECATED_2.107@@@
deprecated("internal alias FLOCK was unintentionally available from "
~ "std.stdio and will be removed afer 2.107")
alias FLOCK = __fp_lock;
// @@@DEPRECATED_2.107@@@
deprecated("internal alias FUNLOCK was unintentionally available from "
~ "std.stdio and will be removed afer 2.107")
alias FUNLOCK = __fp_unlock;
// @@@DEPRECATED_2.107@@@
deprecated("internal alias _setmode was unintentionally available from "
~ "std.stdio and will be removed afer 2.107")
alias _setmode = setmode;
// @@@DEPRECATED_2.107@@@
deprecated("internal function _fileno was unintentionally available from "
~ "std.stdio and will be removed afer 2.107")
fileno_t _fileno(FILE* f) { return f._file; }
}
else version (CRuntime_Microsoft)
{
private alias _FPUTC = _fputc_nolock;
private alias _FPUTWC = _fputwc_nolock;
private alias _FGETC = _fgetc_nolock;
private alias _FGETWC = _fgetwc_nolock;
private alias _FLOCK = _lock_file;
private alias _FUNLOCK = _unlock_file;
// @@@DEPRECATED_2.107@@@
// Remove this once the deprecation phase for CRuntime_DigitalMars has ended.
private alias __setmode = _setmode;
// @@@DEPRECATED_2.107@@@
deprecated("internal alias FPUTC was unintentionally available from "
~ "std.stdio and will be removed afer 2.107")
alias FPUTC = _fputc_nolock;
// @@@DEPRECATED_2.107@@@
deprecated("internal alias FPUTWC was unintentionally available from "
~ "std.stdio and will be removed afer 2.107")
alias FPUTWC = _fputwc_nolock;
// @@@DEPRECATED_2.107@@@
deprecated("internal alias FGETC was unintentionally available from "
~ "std.stdio and will be removed afer 2.107")
alias FGETC = _fgetc_nolock;
// @@@DEPRECATED_2.107@@@
deprecated("internal alias FGETWC was unintentionally available from "
~ "std.stdio and will be removed afer 2.107")
alias FGETWC = _fgetwc_nolock;
// @@@DEPRECATED_2.107@@@
deprecated("internal alias FLOCK was unintentionally available from "
~ "std.stdio and will be removed afer 2.107")
alias FLOCK = _lock_file;
// @@@DEPRECATED_2.107@@@
deprecated("internal alias FUNLOCK was unintentionally available from "
~ "std.stdio and will be removed afer 2.107")
alias FUNLOCK = _unlock_file;
}
else version (CRuntime_Glibc)
{
private alias _FPUTC = fputc_unlocked;
private alias _FPUTWC = fputwc_unlocked;
private alias _FGETC = fgetc_unlocked;
private alias _FGETWC = fgetwc_unlocked;
private alias _FLOCK = core.sys.posix.stdio.flockfile;
private alias _FUNLOCK = core.sys.posix.stdio.funlockfile;
// @@@DEPRECATED_2.107@@@
deprecated("internal alias FPUTC was unintentionally available from "
~ "std.stdio and will be removed afer 2.107")
alias FPUTC = fputc_unlocked;
// @@@DEPRECATED_2.107@@@
deprecated("internal alias FPUTWC was unintentionally available from "
~ "std.stdio and will be removed afer 2.107")
alias FPUTWC = fputwc_unlocked;
// @@@DEPRECATED_2.107@@@
deprecated("internal alias FGETC was unintentionally available from "
~ "std.stdio and will be removed afer 2.107")
alias FGETC = fgetc_unlocked;
// @@@DEPRECATED_2.107@@@
deprecated("internal alias FGETWC was unintentionally available from "
~ "std.stdio and will be removed afer 2.107")
alias FGETWC = fgetwc_unlocked;
// @@@DEPRECATED_2.107@@@
deprecated("internal alias FLOCK was unintentionally available from "
~ "std.stdio and will be removed afer 2.107")
alias FLOCK = core.sys.posix.stdio.flockfile;
// @@@DEPRECATED_2.107@@@
deprecated("internal alias FUNLOCK was unintentionally available from "
~ "std.stdio and will be removed afer 2.107")
alias FUNLOCK = core.sys.posix.stdio.funlockfile;
}
else version (GENERIC_IO)
{
nothrow:
@nogc:
extern (C) private
{
static import core.stdc.wchar_;
pragma(mangle, fputc.mangleof) int _FPUTC(int c, _iobuf* fp);
pragma(mangle, core.stdc.wchar_.fputwc.mangleof) int _FPUTWC(wchar_t c, _iobuf* fp);
pragma(mangle, fgetc.mangleof) int _FGETC(_iobuf* fp);
pragma(mangle, core.stdc.wchar_.fgetwc.mangleof) int _FGETWC(_iobuf* fp);
}
version (Posix)
{
private alias _FLOCK = core.sys.posix.stdio.flockfile;
private alias _FUNLOCK = core.sys.posix.stdio.funlockfile;
}
else
{
static assert(0, "don't know how to lock files on GENERIC_IO");
}
// @@@DEPRECATED_2.107@@@
deprecated("internal function fputc_unlocked was unintentionally available "
~ "from std.stdio and will be removed afer 2.107")
extern (C) pragma(mangle, fputc.mangleof) int fputc_unlocked(int c, _iobuf* fp);
// @@@DEPRECATED_2.107@@@
deprecated("internal function fputwc_unlocked was unintentionally available "
~ "from std.stdio and will be removed afer 2.107")
extern (C) pragma(mangle, core.stdc.wchar_.fputwc.mangleof) int fputwc_unlocked(wchar_t c, _iobuf* fp);
// @@@DEPRECATED_2.107@@@
deprecated("internal function fgetc_unlocked was unintentionally available "
~ "from std.stdio and will be removed afer 2.107")
extern (C) pragma(mangle, fgetc.mangleof) int fgetc_unlocked(_iobuf* fp);
// @@@DEPRECATED_2.107@@@
deprecated("internal function fgetwc_unlocked was unintentionally available "
~ "from std.stdio and will be removed afer 2.107")
extern (C) pragma(mangle, core.stdc.wchar_.fgetwc.mangleof) int fgetwc_unlocked(_iobuf* fp);
// @@@DEPRECATED_2.107@@@
deprecated("internal alias FPUTC was unintentionally available from "
~ "std.stdio and will be removed afer 2.107")
alias FPUTC = fputc_unlocked;
// @@@DEPRECATED_2.107@@@
deprecated("internal alias FPUTWC was unintentionally available from "
~ "std.stdio and will be removed afer 2.107")
alias FPUTWC = fputwc_unlocked;
// @@@DEPRECATED_2.107@@@
deprecated("internal alias FGETC was unintentionally available from "
~ "std.stdio and will be removed afer 2.107")
alias FGETC = fgetc_unlocked;
// @@@DEPRECATED_2.107@@@
deprecated("internal alias FGETWC was unintentionally available from "
~ "std.stdio and will be removed afer 2.107")
alias FGETWC = fgetwc_unlocked;
version (Posix)
{
// @@@DEPRECATED_2.107@@@
deprecated("internal alias FLOCK was unintentionally available from "
~ "std.stdio and will be removed afer 2.107")
alias FLOCK = core.sys.posix.stdio.flockfile;
// @@@DEPRECATED_2.107@@@
deprecated("internal alias FUNLOCK was unintentionally available from "
~ "std.stdio and will be removed afer 2.107")
alias FUNLOCK = core.sys.posix.stdio.funlockfile;
}
}
else
{
static assert(0, "unsupported C I/O system");
}
private extern (C) @nogc nothrow
{
pragma(mangle, _FPUTC.mangleof) int trustedFPUTC(int ch, _iobuf* h) @trusted;
version (CRuntime_DigitalMars)
pragma(mangle, _FPUTWC.mangleof) int trustedFPUTWC(int ch, _iobuf* h) @trusted;
else
pragma(mangle, _FPUTWC.mangleof) int trustedFPUTWC(wchar_t ch, _iobuf* h) @trusted;
}
//------------------------------------------------------------------------------
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.read : 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, "'"));
}
}
}
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
import std.stdio;
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 @nogc nothrow
{
import core.stdc.stdlib : malloc;
assert(!_p);
_p = cast(Impl*) malloc(Impl.sizeof);
if (!_p)
{
import core.exception : onOutOfMemoryError;
onOutOfMemoryError();
}
initImpl(handle, name, refs, isPopened);
}
private void initImpl(FILE* handle, string name, uint refs = 1, bool isPopened = false) @nogc nothrow pure @safe
{
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
$(CSTDIO 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 (https://issues.dlang.org/show_bug.cgi?id=14422)
version (CRuntime_Microsoft)
{
setAppendWin(stdioOpenmode);
}
}
/// ditto
this(R1, R2)(R1 name)
if (isSomeFiniteCharInputRange!R1)
{
import std.conv : to;
this(name.to!string, "rb");
}
/// ditto
this(R1, R2)(R1 name, R2 mode)
if (isSomeFiniteCharInputRange!R1 &&
isSomeFiniteCharInputRange!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 pure nothrow @nogc
{
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.
*/
ref File opAssign(File rhs) @safe return
{
import std.algorithm.mutation : swap;
swap(this, rhs);
return this;
}
// https://issues.dlang.org/show_bug.cgi?id=20129
@safe unittest
{
File[int] aa;
aa.require(0, File.init);
}
/**
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 $(CSTDIO fopen) function.
Throws: `ErrnoException` in case of error.
*/
void open(string name, scope const(char)[] stdioOpenmode = "rb") @trusted
{
resetFile(name, stdioOpenmode, false);
}
// https://issues.dlang.org/show_bug.cgi?id=20585
@system unittest
{
File f;
try
f.open("doesn't exist");
catch (Exception _e)
{
}
assert(!f.isOpen);
f.close(); // to check not crash here
}
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();
}
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, "'"));
}
_p = cast(Impl*) enforce(malloc(Impl.sizeof), "Out of memory");
initImpl(handle, name, 1, isPopened);
version (CRuntime_Microsoft)
{
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)
{
auto handle = _p.handle;
_p.handle = null;
// fclose disassociates the FILE* even in case of error (https://issues.dlang.org/show_bug.cgi?id=19751)
errnoEnforce(.fclose(handle) == 0,
"Could not close file `"~_name~"'");
}
}
version (CRuntime_Microsoft)
{
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 $(CSTDIO 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;
}
@safe 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
@safe 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), then attempts to
associate the given file descriptor with the `File`, and sets the file's name to `null`.
The mode must be compatible with the mode of the file descriptor.
Throws: `ErrnoException` in case of error.
Params:
fd = File descriptor to associate with this `File`.
stdioOpenmode = Mode to associate with this File. The mode has the same semantics
semantics as in the C standard library $(CSTDIO fdopen) function,
and must be compatible with `fd`.
*/
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 (CRuntime_DigitalMars)
{
// 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.
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 (CRuntime_Microsoft)
{
auto fp = _fdopen(fd, modez);
errnoEnforce(fp);
}
else version (Posix)
{
import core.sys.posix.stdio : fdopen;
auto fp = fdopen(fd, modez);
errnoEnforce(fp);
}
else
static assert(0, "no fdopen() available");
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 (CRuntime_DigitalMars)
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 $(CSTDIO 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 last used to initialize this `File`, if any.
Some functions that create or initialize the `File` set the name field to `null`.
Examples include $(LREF tmpfile), $(LREF wrapFile), and $(LREF fdopen). See the
documentation of those functions for details.
Returns: The name last used to initialize this this file, or `null` otherwise.
*/
@property string name() const @safe pure nothrow return