File.byLine for either Windows / Unix newlines

Dennis dkorpel at gmail.com
Mon Dec 11 15:40:00 UTC 2017


I'm on Windows and I recently got confused by how Phobos 
functions handle newlines.

```
void main() {
     import std.stdio;
     import std.path : buildPath, tempDir;

     auto path = buildPath(tempDir(), "test.txt");
     auto file = new File(path, "w");

     file.write("hello there!\n");   //actually writes hello 
there!\r\n
     file.write('\n');               //actually writes \r\n
     file.rawWrite("\n");            //actually writes \n
     //file.rawWrite('\n');          //doesn't compile
     file.close();

     //byLine uses \n as default terminator, so a trailing \r is 
kept
     writeln(File(path).byLine.front~"huh?");   //prints "huh?o 
there!"
}
```

- Why do these functions behave like that?
- What is the easiest way to iterate over a file by line that 
works with both \r\n and \n line endings? I prefer not to write a 
new method for this.





More information about the Digitalmars-d-learn mailing list