File() vs. std.cstream.din
Regan Heath
regan at netwin.co.nz
Thu Apr 20 15:04:35 PDT 2006
On Thu, 20 Apr 2006 20:36:22 +0000 (UTC), Gerome Fournier
<Gerome_member at pathlink.com> wrote:
> The following code doesn't behave the same if I output a file by
> opening it, or through std.cstream.din. I get an extra line when using
> std.cstream.din, and I'd like to understand why.
>
> Here goes the code first to show the problem:
<snip>
> Why do I get an extra line here?
My guess is that it is related to when eof is flagged. In the File case it
reads the last line and flags eof, in the case of din it has to read past
the end to flag eof. If you modify the code to be:
void dump_stream(Stream s)
{
while (!s.eof()) {
char[] line = s.readLine();
if (line !is null) printf("Line: %.*s\n", line);
}
}
you will get the same results for both, this handles the attempt to read
past the end (which results in a null char[] array AKA a non-existant line
- as opposed to an empty line - see p.s. below).
Regan
(to flog again that horse I have previously flogged..)
p.s. You might also notice that without the current distinction between a
null array and an empty array you would not be able to distinguish this
case. You would have to change readLine to return a bool or similar, not
that that is such a bad idea, a readLine function that re-used a buffer
might be more efficient, eg.
bool readLine(inout char[] line);
More information about the Digitalmars-d
mailing list