Range violation error when reading from a file

Norm norm.rowtree at gmail.com
Mon Jun 17 03:46:11 UTC 2019


On Monday, 17 June 2019 at 00:22:23 UTC, Samir wrote:
> On Sunday, 16 June 2019 at 23:55:41 UTC, lithium iodate wrote:
>> There is *very* likely to be a terminating new-line at the end 
>> of the file (many editors add one without asking!). If that 
>> the case, the last line seen by the loop will be empty and you 
>> must not attempt to access any elements.
>
> On Monday, 17 June 2019 at 00:02:37 UTC, aliak wrote:
>> The fail bit is only set after reading fails. So after you 
>> read the last line, your eof will still return true, and hence 
>> your range violation.
>
> Hmmmm...maybe you and lithium iodate were onto something.
>
> Here is what the file looks like in vim:
>     > line 1
>     line 2
>     line 3
>     > line 4
>     line 5
>     ~
>     ~
>     ~
>
> The "5" in the last line is the last character I can put my 
> cursor on.
>
> Also, if I run the program below with the same file, I don't 
> get any range violation errors:
>
> import std.stdio;
> import std.string;
>
> void main() {
>     File file = File("test.txt");
>     string line;
>
>     while (!file.eof()) {
>         line = file.readln().strip;
>         //if (line[0] == '>') {         // line 10
>         //    writeln(line[1..$]);
>         //}
>         //else {
>             writeln(line);
>         //}
>     }
> }
>
> HOWEVER, the output is interesting.  There IS a blank line 
> between the last line and the prompt:
>
>     $ dmd -run readfile.d
>     > line 1
>     line 2
>     line 3
>     > line 4
>     line 5
>
>     $
>
> Any suggestions on how to rectify?

You could change the IF to

`if(line.length > 0 && line[0] == '>')`

or use strip itself;

`File("test.txt", "r").byLine.map!(line => 
line.strip(">")).writeln;`

For "> line 1" your code and this above will generate " line 1" 
(note the leading space). To remove that change the string passed 
to `strip` to include a space, e.g.;

`.strip("> ")).writeln;`

bye,
Norm



More information about the Digitalmars-d-learn mailing list