Reputation: 1951
I have a very very simple example:
content = [0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x0D, 0x0A] # "Hello\r\n"
f = File.new("PATH", "w")
content.each {|b| f.write(b.chr)}
f.close
I tried to write something to files and then I discovered, that Ruby writes for each \r
a \r
and for each \n
a \r\n
. So when I run my code example, Ruby doesn't write Hello\r\n
into the file, it writes Hello\r\r\n
. Is there a way to prevent this or to write each byte without adding other bytes?
Upvotes: 1
Views: 155
Reputation: 118261
The reason mentioned in the documentation IO Open Mode
"b" - Binary file mode. Suppresses EOL <-> CRLF conversion on Windows and sets external encoding to ASCII-8BIT unless explicitly specified.
Thus you need to use 'wb'
instead of 'w'
to resolve your issue.
You can write code something like below :
content = [0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x0D, 0x0A] # "Hello\r\n"
f = File.new("PATH", "wb")
content.each {|b| f.write(b.chr)}
f.close
Upvotes: 4