Thread overview
File.write introduces \r regardless of presence
Jul 16, 2022
HuskyNator
Jul 16, 2022
Adam D Ruppe
Jul 16, 2022
HuskyNator
July 16, 2022

While trying to figure out why my reading from & write back to file kept increasing the size of my entries, I figured out File.write always introduces a \r character before any \n characters, even if they are already preceded by one.

Is this intentional behaviour or an oversight?

Example:

module app;
import std.stdio;
import std.file;

void main(string[] args) {
	string a = "`a\r\n\r\nb`\r\n";
	File("test.txt", "w").write(a);
}

Content of text.txt:

`a\r\r\n\r\r\nb\`\r\r\n
July 16, 2022

On Saturday, 16 July 2022 at 19:54:08 UTC, HuskyNator wrote:

>

File("test.txt", "w").write(a);

The default here is write in text mode, change the "w" to "wb" and it won't molest your line endings any more.

July 16, 2022

On Saturday, 16 July 2022 at 20:08:38 UTC, Adam D Ruppe wrote:

>

The default here is write in text mode, change the "w" to "wb" and it won't molest your line endings any more.

Thank you, that worked.

This raises 3 questions for me.

  1. Are there any nasty pitfalls with this change that might force me to find a workaround? (eg. en/decoding issues or the like?)

  2. Does this mean readText reads in binary mode?

  3. The documentation refers to the same semantics as in the C standard library fopen function, would this also include the "x" subspecifier in C2011?
    I'm not sure having documentation depend on other documentation that may change was a good idea...

July 17, 2022

On Saturday, 16 July 2022 at 20:46:00 UTC, HuskyNator wrote:
is raises 3 questions for me.

>
  1. Are there any nasty pitfalls with this change that might force me to find a workaround? (eg. en/decoding issues or the like?)

This is strictly a C mechanism, and only on Windows. So refer to the C documentation on said pitfalls.

>
  1. Does this mean readText reads in binary mode?

readText comes from std.file, and basically just reads a file into an array of char[] instead of an array of ubyte[]. It does no translation for line endings. It does validate the text is valid utf and makes sure the BOM is correct.

>
  1. The documentation refers to the same semantics as in the C standard library fopen function, would this also include the "x" subspecifier in C2011?

D directly calls fopen from C, so I would imagine this is true if you use a C library that has the subspecifier.

-Steve