How to Handle Line Endings Across Platforms in Rust
Rust uses the platform's native line endings by default, but you can normalize them to LF (\n) for cross-platform consistency using the replace method on strings or the BufRead trait for files.
let normalized = input.replace("\r\n", "\n").replace("\r", "\n");
For reading files line-by-line while ignoring platform differences, use lines() which handles \n, \r\n, and \r automatically:
use std::io::{BufRead, BufReader};
use std::fs::File;
let file = File::open("input.txt").unwrap();
let reader = BufReader::new(file);
for line in reader.lines() {
let line = line.unwrap();
// Process line without worrying about \r or \n
}
If you need to write files with specific line endings, explicitly append \n (LF) for Unix/Mac or \r\n (CRLF) for Windows:
use std::io::Write;
use std::fs::File;
fn main() {
let mut file = File::create("output.txt").unwrap();
file.write_all(b"Line 1\n").unwrap(); // LF for Unix
file.write_all(b"Line 2\r\n").unwrap(); // CRLF for Windows
}
For robust cross-platform text processing, consider using the nom or regex crates to parse line endings explicitly if custom logic is required.