HaxeFoundation / haxe

Haxe - The Cross-Platform Toolkit
https://haxe.org
6.16k stars 656 forks source link

FileInput.readLine() fails if last line is empty #5418

Open sebthom opened 8 years ago

sebthom commented 8 years ago

The following code fails on all sys targets with an EOF exception, but shouldn't because before invoking readLine the EOF status is tested.

class Test {
    static function main() {
        sys.io.File.saveContent("test.txt", "line1\nline2\n");
        var is = sys.io.File.read("test.txt", false);
        while (!is.eof()) {
            trace(is.readLine());
        }
        is.close();
    }
}

The example works if

        sys.io.File.saveContent("test.txt", "line1\nline2\n");

is replaced by

        sys.io.File.saveContent("test.txt", "line1\nline2");
sebthom commented 8 years ago

The current behavior is especially tiring because a try/finally clause doesn't exist (yet) in Haxe. So to read all lines one-by-one properly, atm in Haxe one would have to do:

 static function main() {
        var is = sys.io.File.read("test.txt", false);
        try {
            while (true) {
                trace(is.readLine());
            }
        } catch (e: Eof) {
           // expected
           is.close();
        } catch (e: Dynamic) {
           is.close();
           #if neko neko.Lib.rethrow #else throw #end (e);
        }
}

That is a lot of boiler plate code and exception driven flow-control is really bad coding practice!

Simn commented 8 years ago

readLine catches Eof and then does this:

if( s.length == 0 )
    #if neko neko.Lib.rethrow #else throw #end (e);

This code is ancient so I'll not touch it for 3.3, but I agree something is wrong here.

jonasmalacofilho commented 6 years ago

This relates to #3611: --interp fileInput.eof() bug.

FileInput.eof() follows the behavior of C's feof and "only returns true if we tried to read past the file end."