File Api [Was: [your code here]]

Timon Gehr timon.gehr at gmx.ch
Fri Feb 17 18:44:11 PST 2012


On 02/18/2012 03:20 AM, bearophile wrote:
> H. S. Teoh:
>
>> P.S.S. The .idup is a bit ugly, but necessary, since apparently byLine()
>> calls readln() with a static buffer, so choice will be silently
>> overwritten if the .idup is omitted.
>
> An alternative File API that to me looks nice. This is a first part, it's for scripting-like or not high performance purposes, it looks essentially like Python code, every line is a newly allocated string:
>
> import std.stdio;
> void main() {
>      string[] lines;
>      foreach (line; File("data.dat")) {
>          static assert(is(line == string));
>          lines ~= line;
>      }
> }
>
> If you don't want a new buffer every line you use something like this:
>
> import std.stdio;
> void main() {
>      string[] lines;
>      foreach (line; File("data.dat").fastLines()) {
>          static assert(is(line == char[]));
>          lines ~= line.idup;
>      }
> }
>
> So on default it's handy, short and safe, and with a method you avoid an allocation every line and get a mutable char[].
>
> Maybe even this works, downloads a page and scans its lines, but maybe it's better to add a bit of extra safety to this:
> foreach (line; File("http://www.dlang.org/faq.html")) {}
>
> Bye,
> bearophile

Note that what we have now is clear, handy, quite short and safe and 
efficient. What you propose takes away the clarity and efficiency parts. 
foreach(foo; File("data.dat")) {} // by what does this iterate?


More information about the Digitalmars-d mailing list