I am running Ruby 1.9.3 on Windows. When I run the following snippet of code
text = File.read(path)
File.write(path, text)
I get the exact same file when the file has CR+LF line endings. When I run this on a file with LF line endings, it changes to CR+LF line endings.
How can I read from and write to a file using Ruby on Windows such that line endings are preserved, whether CR+LF or LF?
Ruby, along with Perl and probably Python, are aware of the OS the code is running on, and will automatically set what the line-endings should be.
If you read, then write, a text file, those settings will kick in, and you'll see the file change like you are.
If you need to have the file be unchanged, add a b
flag to an open
statement, like:
File.open('path', 'wb') do |fo|
fo.write(text)
end
For more information, see "IO Open Mode".
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