File Api [Was: [your code here]]

bearophile bearophileHUGS at lycos.com
Fri Feb 17 19:19:41 PST 2012


Timon Gehr:

> 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. 

What we have now:
- by Line() is explicit, but if you don't use it is not that clear, if a Python programmer iterates on File it gives an almost mysterious error message:
test.d(4): Error: invalid foreach aggregate (File __ctmp834 = 0;

 , __ctmp834).this("data.dat","rb")
- It's less handy because you have to add idup if you need strings (and most times you need a string);
- It's longer than what I have suggested;
- It's not safe, because if you need to work mutable char[], it yields the same buffer. This is a bug-prone default. A better API allocates every line on default, and not allocates it on request. (This is how I designed my dlibs1). It's "safe" only if you need a string, because it forces you to convert it to a string with idup.


> foreach(foo; File("data.dat")) {} // by what does this iterate?

Iterating the lines of a file is a very common operation, so you remember what it does.

Anyway, if you don't like File to be iterable, I'd like that attempt to give better error message, and byLine() to yield a newly allocated string (and another "fast"-annotated method that yields a slice of the same mutable buffer).

Bye,
bearophile


More information about the Digitalmars-d mailing list