File

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.

struct File {}

Constructors

this
this(string name, in char[] stdioOpenmode = "rb")
this(R1 name)
this(R1 name, R2 mode)

Constructor taking the name of the file to open and the open mode.

Destructor

A destructor is present on this object, but not explicitly documented in the source.

Postblit

A postblit is present on this object, but not explicitly documented in the source.

Members

Functions

byChunk
auto byChunk(size_t chunkSize)
ByChunk byChunk(ubyte[] buffer)

Returns an input range set up to read from the file handle a chunk at a time.

byLine
auto byLine(KeepTerminator keepTerminator = No.keepTerminator, Terminator terminator = '\n')
auto byLine(KeepTerminator keepTerminator, Terminator terminator)

Returns an input range set up to read from the file handle one line at a time.

byLineCopy
auto byLineCopy(KeepTerminator keepTerminator = No.keepTerminator, Terminator terminator = '\n')
auto byLineCopy(KeepTerminator keepTerminator, Terminator terminator)

Returns an input range set up to read from the file handle one line at a time. Each line will be newly allocated. front will cache its value to allow repeated calls without unnecessary allocations.

clearerr
void clearerr()

If the file is not opened, succeeds vacuously. Otherwise, returns clearerr for the file handle.

close
void close()

If the file was unopened, succeeds vacuously. Otherwise closes the file (by calling fclose), throwing on error. Even if an exception is thrown, afterwards the 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.

detach
void detach()

Detaches from the underlying file. If the sole owner, calls close.

fdopen
void fdopen(int fd, in char[] stdioOpenmode = "rb")

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.

flush
void flush()

Flushes the C FILE buffers.

getFP
FILE* getFP()

Returns the FILE* corresponding to this object.

lock
void lock(LockType lockType = LockType.readWrite, ulong start = 0, ulong length = 0)

Locks the specified file segment. If the file segment is already locked by another process, waits until the existing lock is released. If both start and length are zero, the entire file is locked.

lockingBinaryWriter
auto lockingBinaryWriter()

Returns an output range that locks the file and allows fast writing to it.

lockingTextWriter
auto lockingTextWriter()

Returns an output range that locks the file and allows fast writing to it.

opAssign
void opAssign(File rhs)

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.

open
void open(string name, in char[] stdioOpenmode = "rb")

First calls detach (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 fopen function.

popen
void popen(string command, in char[] stdioOpenmode = "r")

First calls detach (throwing on failure), and then runs a command by calling the C standard library function popen.

rawRead
T[] rawRead(T[] buffer)

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

rawWrite
void rawWrite(in T[] buffer)

Calls fwrite for the file handle. The number of items to write and the size of each item is inferred from the size and type of the input array, respectively. An error is thrown if the buffer could not be written in its entirety.

readf
uint readf(in char[] format, auto ref Data data)

Read data from the file according to the specified format specifier using std.format.formattedRead.

readln
S readln(dchar terminator = '\n')

Read line from the file handle and return it as a specified type.

readln
size_t readln(ref C[] buf, dchar terminator = '\n')
size_t readln(ref C[] buf, R terminator)

Read line from the file handle and write it to buf[], including terminating character.

reopen
void reopen(string name, in char[] stdioOpenmode = "rb")

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 freopen function.

rewind
void rewind()

Calls rewind for the file handle.

seek
void seek(long offset, int origin = SEEK_SET)

Calls fseek for the file handle.

setvbuf
void setvbuf(size_t size, int mode = _IOFBF)

Calls setvbuf for the file handle.

setvbuf
void setvbuf(void[] buf, int mode = _IOFBF)

Calls setvbuf for the file handle.

sync
void sync()

Forces any data buffered by the OS to be written to disk. Call flush before calling this function to flush the C FILE buffers first.

tryLock
bool tryLock(LockType lockType = LockType.readWrite, ulong start = 0, ulong length = 0)

Attempts to lock the specified file segment. If both start and length are zero, the entire file is locked.

unlock
void unlock(ulong start = 0, ulong length = 0)

Removes the lock over the specified file segment.

windowsHandle
HANDLE windowsHandle()

Returns the underlying operating system HANDLE (Windows only).

windowsHandleOpen
void windowsHandleOpen(HANDLE handle, in char[] stdioOpenmode)

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.

write
void write(S args)

Writes its arguments in text format to the file.

writef
void writef(in Char[] fmt, A args)

Writes its arguments in text format to the file, according to the format in the first argument.

writefln
void writefln(in Char[] fmt, A args)

Writes its arguments in text format to the file, according to the format in the first argument, followed by a newline.

writeln
void writeln(S args)

Writes its arguments in text format to the file, followed by a newline.

Properties

eof
bool eof [@property getter]

Returns true if the file is at end (see feof).

error
bool error [@property getter]

If the file is not opened, returns true. Otherwise, returns ferror for the file handle.

fileno
int fileno [@property getter]

Returns the file number corresponding to this object.

isOpen
bool isOpen [@property getter]

Returns true if the file is opened.

name
string name [@property getter]

Returns the name of the last opened file, if any. If a File was created with tmpfile and wrapFile it has no name.

size
ulong size [@property getter]

Get the size of the file, ulong.max if file is not searchable, but still throws if an actual error occurs.

tell
ulong tell [@property getter]

Calls ftell for the managed file handle.

Static functions

tmpfile
File tmpfile()

Returns a temporary file by calling tmpfile. Note that the created file has no name.

wrapFile
File wrapFile(FILE* f)

Unsafe function that wraps an existing FILE*. The resulting File never takes the initiative in closing the file. Note that the created file has no name

Templates

byRecord
template byRecord(Fields...)

Creates an input range set up to parse one line at a time from the file into a tuple.

Examples

1 // test.d
2 void main(string[] args)
3 {
4     auto f = File("test.txt", "w"); // open for writing
5     f.write("Hello");
6     if (args.length > 1)
7     {
8         auto g = f; // now g and f write to the same file
9                     // internal reference count is 2
10         g.write(", ", args[1]);
11         // g exits scope, reference count decreases to 1
12     }
13     f.writeln("!");
14     // f exits scope, reference count falls to zero,
15     // underlying $(D FILE*) is closed.
16 }
% rdmd test.d Jimmy
% cat test.txt
Hello, Jimmy!
% __

Meta

Suggestion Box / Bug Report