Does println write \n or \r\n on Windows in EK9?

← Common String Operations · Ref: Q2286

println ends a line with \n (LF) on every platform, Windows included, so a program writes the same bytes everywhere - to Stdout, Stderr and a TextFile alike. Pretty-printed JSON uses \n too.

  stdout.println("same bytes on every platform")   //ends with \n

WANTING CR/LF

A program that needs CR/LF (\r\n) - a file for a tool that insists on it - writes the line end itself with print:

  crlf <- "\r\n"
  stdout.print("ends with CR/LF" + crlf)

The two characters are code points 13 (CR) and 10 (LF). println and print mix freely in one output.

NO SETTING

There is no option or environment variable that changes what println writes: a setting would make a program's output depend on the machine it ran on. Where CR/LF is wanted, it is in the source, where anyone reading it can see it.

THE ONE EXCEPTION: SOCKETS

println on a TCP connection's output writes \r\n on every platform, because the network line protocols (HTTP/1.1, SMTP and others) require it.

Reading is unaffected: reading a text line by line gives the line without its end, whether it was \n or \r\n.

See Q3 for printing to the console. See Q154 for reading a file line by line.

Example

#!ek9
defines module qa.stringops.lineends

  defines program

    LineEnds()
      stdout <- Stdout()

      stdout.println("println ends this line with LF on every platform")

      crlf <- "\r\n"
      stdout.print("this line ends with CR/LF because the program wrote it" + crlf)

      carriageReturn <- #< crlf
      lineFeed <- #> crlf
      stdout.println(`a CR/LF line end is ${length crlf} characters: code points ${carriageReturn.codePoint()} and ${lineFeed.codePoint()}`)

      text <- `first${crlf}second${crlf}`
      stdout.println(`a two-line CR/LF text is ${length text} characters`)
Other ways to ask this
  • How do I write CR/LF line endings in EK9?
  • Why does my EK9 program not write Windows line endings?
  • Can I make EK9 println use the platform line separator?
  • Is there a setting for the line separator in EK9?
  • How do I write a file with \r\n line endings in EK9?

Coming from another language?

Go: fmt.Println writes \n on every platform; write \r\n yourself. Rust: println! and writeln! write \n on every platform. EK9 is the same. Java: println writes System.lineSeparator(), \r\n on Windows. C#: Console.WriteLine and Environment.NewLine are \r\n on Windows. Python 3: print writes \n, but a file or stdout opened in text mode turns it into \r\n on Windows (newline='' prevents it). C: \n in a text-mode stream becomes \r\n on Windows.

Keywords: CRLF, LF, Windows, carriage return, line end, line ending, line separator, lineSeparator, newline, print, println