Read Complete File to Array of Lines

Graham Fawcett fawcett at uwindsor.ca
Fri May 11 10:58:24 PDT 2012


On Friday, 11 May 2012 at 15:18:11 UTC, H. S. Teoh wrote:
> On Fri, May 11, 2012 at 05:00:16PM +0200, Paul wrote:
>> I would like to read a complete file in one statement and then
>> process it line by line.
>> 
>> foreach (line; MyFile)
>> etc.
>> 
>> Is it possible to read a file into and array of lines?
>
> import std.array;
> import std.stdio;
>
> string[] getLines(File f) {
> 	auto a = appender!string;
> 	foreach (line; f.byLine()) {
> 		a.put(line);
> 	}
> 	return a.data;
> }

Does that work? I think you mean:

string[] getLines(File f) {
   auto a = appender!(string[]);
   foreach (line; f.byLine()) {
     a.put(line.idup);
   }
   return a.data;
}

You could also write:

string[] getLines(File f)
{
   return array(map!"a.idup"(f.byLine));
}

Or

{
   return f.byLine.map!"a.idup".array;
}


This may be slower than the appender version, which is optimized 
for performance; I'm not sure.

Graham


More information about the Digitalmars-d-learn mailing list