MATLAB: Writing newline to binary file with 16-bit Unicode

16-bitbinary fileunicode

I'm trying to export text to a txt-file using 16-bit unicode. Everything works fine except new lines. Whatever trick I try (e.g. char(10)) is converted to 0d 0a (13 10) in the output file, which is not the correct 16-bit syntax and thus not compatible. Is there anyway to get around this?
A small example:
fid = fopen('output.txt','wt');
for k = 1:length(text)
encoded_str = double(unicode2native(text{k},'UTF8'));
if k == 1
fwrite(fid,[255 254],'uint8',0,'l');
end
fwrite(fid,encoded_str,'uint16',0,'l');
fwrite(fid,[13 0 10 0],'uint8',0,'l');
end
fclose(fid);

Best Answer

The problem is that you opened in text mode when you specified 'wt' -- the 't' part means text. Text mode is required to translate newline to carriage return followed by newline. Use 'w' instead of 'wt' to disable that.