View source code
Display the source code in std/stdio.d from which this page was generated on github.
Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using local clone.

Function std.stdio.File.byChunk

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

std.stdio.File.ByChunkImpl byChunk (
  ulong chunkSize
);

std.stdio.File.ByChunkImpl byChunk (
  ubyte[] buffer
);

The element type for the range will be ubyte[]. Range primitives may throw StdioException on I/O error.

Example

void main()
{
    // Read standard input 4KB at a time
    foreach (ubyte[] buffer; stdin.byChunk(4096))
    {
        ... use buffer ...
    }
}

The parameter may be a number (as shown in the example above) dictating the size of each chunk. Alternatively, byChunk accepts a user-provided buffer that it uses directly.

Example

void main()
{
    // Read standard input 4KB at a time
    foreach (ubyte[] buffer; stdin.byChunk(new ubyte[4096]))
    {
        ... use buffer ...
    }
}

In either case, the content of the buffer is reused across calls. That means front will not persist after popFront is called, so if retention is needed, the caller must copy its contents (e.g. by calling buffer.dup).

In the example above, buffer.length is 4096 for all iterations, except for the last one, in which case buffer.length may be less than 4096 (but always greater than zero).

With the mentioned limitations, byChunk works with any algorithm compatible with input ranges.

Example

// Efficient file copy, 1MB at a time.
import std.algorithm, std.stdio;
void main()
{
    stdin.byChunk(1024 * 1024).copy(stdout.lockingTextWriter());
}

joiner can be used to join chunks together into a single range lazily.

Example

import std.algorithm, std.stdio;
void main()
{
    //Range of ranges
    static assert(is(typeof(stdin.byChunk(4096).front) == ubyte[]));
    //Range of elements
    static assert(is(typeof(stdin.byChunk(4096).joiner.front) == ubyte));
}

Returns

A call to byChunk returns a range initialized with the File object and the appropriate buffer.

Throws

If the user-provided size is zero or the user-provided buffer is empty, throws an Exception. In case of an I/O error throws StdioException.

Authors

Walter Bright, Andrei Alexandrescu, Alex Rønne Petersen

License

Boost License 1.0.