View source code
Display the source code in std/file.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.file.slurp

Reads a file line by line and parses the line into a single value or a Tuple of values depending on the length of Types. The lines are parsed using the specified format string. The format string is passed to formattedRead, and therefore must conform to the format string specification outlined in std.format.

Select!(Types.length==1,Types[0][],Tuple!Types[]) slurp(Types...) (
  string filename,
  in char[] format
);

Parameters

NameDescription
Types the types that each of the elements in the line should be returned as
filename the name of the file to read
format the format string to use when reading

Returns

If only one type is passed, then an array of that type. Otherwise, an array of Tuples.

Throws

Exception if the format string is malformed. Also, throws Exception if any of the lines in the file are not fully consumed by the call to formattedRead. Meaning that no empty lines or lines with extra characters are allowed.

Example

import std.typecons : tuple;

scope(exit)
{
    assert(exists(deleteme));
    remove(deleteme);
}

write(deleteme, "12 12.25\n345 1.125"); // deleteme is the name of a temporary file

// Load file; each line is an int followed by comma, whitespace and a
// double.
auto a = slurp!(int, double)(deleteme, "%s %s");
writeln(a.length); // 2
writeln(a[0]); // tuple(12, 12.25)
writeln(a[1]); // tuple(345, 1.125)

Authors

Walter Bright, Andrei Alexandrescu, Jonathan M Davis

License

Boost License 1.0.