File#each_line omits last byte (==\0) if encoding is utf-16
If File#each_line was given utf-16 encoded file with 'rb:utf-16', each line lacks the last one byte.
For example if the line is "a\0\r\0\n\0" in binary, the read line contains "a\0\r\0\r".
See the attchement.
This issue is appear both current 2.1.0 and 2.0.0.
#1 Updated by naruse (Yui NARUSE) about 5 years ago
This is because
- UTF-16 is dummy encoding; you must use UTF-16BE, UTF-16LE, or BOM|UTF-* specifier; OR some other treatment is needed on Ruby.
- default line separator is ASCII \n, not UTF-16 \n. you must explicitly specify UTF-16(BE|LE) \n, or convert to some internal encoding; OR some other special treatment is needed on Ruby
#2 [ruby-core:54181] Updated by arton (Akio Tajima) about 5 years ago
OK, I've fixed my test code. It had some bugs and change the 2nd arg of File#open to 'rb:UTF-16LE'.
Invoking String#rstrip is OK, but can't encode to another encoding from UTF-16LE.
First, I tried to encode utf-16le line to utf-8 using line.rstrip.encode('utf-8') but it failed.
<"This is not a love song."> expected but was
Then I tried to encode the line to CP932 with the code " line.rstrip.encode('cp932') "
The result was an exception.
Encoding::UndefinedConversionError: U+FFFE to Windows-31J in conversion from UTF-16LE to UTF-8 to Windows-31J.
Then I've tried to remove BOM from original line with code below:
p line #=> "\uFFFE"
if line == "\uFFFE" # => false, why ? (maybe BOM is nothing here character, but ...)
line = line[1..-1]
But nothing changes because the condition line == "\uFFFE" was evaluated to false because if I put else clause, the clause run.
Is there any way to encode UTF-16LE to utf-8 or CP932 ?