Macintosh text file with invalid line breaks are created

Vladimir Panteleev via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Sep 28 09:53:24 PDT 2016


On Wednesday, 28 September 2016 at 06:52:51 UTC, Andre Pany wrote:
> Hi,
>
> following application creates a text file with strange content:
>
> void writeTextFile(string filePath, string text)
> {
> 	import std.stdio: File;
> 	auto f = File(filePath, "w");
> 	f.write(text);
> 	f.close();
> }
>
> void main()
> {
> 	import std.ascii: newline;
> 	
> 	string s = "a=1"~newline~"b=2";
> 	writeTextFile("./test.txt", s);
> }
>
> Notepad++ detects the file as macintosh UTF8 file.
> The file has following content:
> a=1CR
> CRLF
> b=2
>
> Where the first CR comes from? Is this a bug?
> dmd v2.071.2 on win10

Since the file is opened in text mode (which is the default), the 
C runtime automatically translates the single \n to a \r\n pair 
when writing the file. Since std.ascii.newline is defined to be 
"\r\n" on Windows, it ends up being written as "\r\r\n".

You could either open the file in binary mode (use "wb" as the 
second argument), or always use "\n" for line separators.



More information about the Digitalmars-d-learn mailing list