reading file byLine

qznc via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Sep 2 07:56:14 PDT 2015


On Wednesday, 2 September 2015 at 13:46:54 UTC, Namal wrote:
> On Wednesday, 2 September 2015 at 13:12:39 UTC, cym13 wrote:
>> 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.
>
> Thx, cym. I have a question about a D strings though. In c++ I 
> would just reuse the string buffer with the "=" how can I clear 
> the string after i store a line in the buffer and do something 
> with it.

Just like in C++: buffer = line;

However, you can just use "line" instead of "buffer" then. The 
byLine does buffer internally, so it overwrites "line" on the 
next iteration of foreach. If you want to keep the line string, 
then make a copy "line.idup".

> I also tried to append a line to an array of strings but it 
> failed because the line is a char?

Here is how to get an array of lines:

import std.stdio;
void main() {
     auto f = File("myfile");
     string buffer[];

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

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


More information about the Digitalmars-d-learn mailing list