reading file byLine

cym13 via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Sep 2 06:12:38 PDT 2015


On Wednesday, 2 September 2015 at 13:01:31 UTC, Namal wrote:
> Hello,
>
> I want to read a file line by line and store each line in a 
> string. I found this example with byLine and ranges. First of 
> all, do I need the range lib at all to do this and if so what 
> is the range of the end of the file?

You don't need the range lib at all, std.range provides advanced 
functions to work with ranges but ranges are a general concept. 
You need std.stdio though as this is doing file operations.

A way to do it is:

void main() {
     auto f = File("myfile");
     string buffer;

     foreach (line ; f.byLine) {
         buffer ~= line;
     }

     f.close();
     writeln(buffer);
}

Note that by default byLine doesn't keep the line terminator. See 
http://dlang.org/phobos/std_stdio.html#.File.byLine for more 
informations.


More information about the Digitalmars-d-learn mailing list