I'm looking for a way to get the platform end of line character sequence (CRLF for Windows, LF for Linux/macOS) at runtime.
I don't believe there is any feature that does this specifically. Even the line-aware features of the standard library don't: BufRead::read_line
is documented to only recognize \n
, and BufRead::lines
(source), which strips end-of-line characters, only does so for \n
and \r\n
, indiscriminate of what platform it's invoked on.
"Platform line ending" is really a category error, though. Files are sent across networks and copied from one computer to another. If your program writes files that need to be opened on Windows in Notepad, it doesn't matter whether the program that generates them is running on Windows or Linux; it needs to emit \r\n
. Similarly if the program is writing a specific file format or implementing some network protocol; the format or protocol should tell you what line separator to use. If the format allows either and there is no convention, pick the one you prefer; just use it consistently.
If you're reading line endings, you should probably tolerate either one, like BufRead::lines
does.
However, should you really need to, like if your output will be read by a poorly written program that expects different line endings on different platforms, you can use conditional compilation attributes to achieve this effect:
#[cfg(windows)]
const LINE_ENDING: &'static str = "\r\n";
#[cfg(not(windows))]
const LINE_ENDING: &'static str = "\n";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With