which encoding should i used with fopen in matlab

9 ビュー (過去 30 日間)
rakia belgacem
rakia belgacem 2019 年 11 月 5 日
回答済み: Saurabh 2025 年 6 月 18 日
the instruction :
fullpathr = strcat (exp_subfolder,tmf_file)
fidr = fopen(fullpathr,r,'ieee-le','UCS-2')
i want to open and read a file in matlab but always it return -1 and warning "the encoding UTF-16 is not supported"
please can any one help me in this
  1 件のコメント
Walter Roberson
Walter Roberson 2025 年 6 月 17 日
This is because MATLAB only officially supports UTF-8 encoding with 'fopen'.
Not exactly. MATLAB supports a long list of encodings, mostly ISO. However, it does not officially support UTF-16

サインインしてコメントする。

回答 (1 件)

Saurabh
Saurabh 2025 年 6 月 18 日
I understand you are encountering an issue opening a UCS‑2 (or UTF‑16) encoded file in MATLAB. This is because MATLAB only officially supports UTF-8 encoding with 'fopen'. While encodings like UCS-2, UTF-16LE are not officially supported.
To workaround this limitation:
Read raw bytes and Decode explicitly.
fid = fopen(fullpathr, 'rb');
fread(fid, 2, '*uint8'); % Skip BOM
bytes = fread(fid, 'uint8=>uint8')';
fclose(fid);
str = native2unicode(bytes, 'UTF-16LE');
data = textscan(str, '%s %f %f', 'Delimiter', ',', 'HeaderLines', 1);
This method reads raw bytes, manually decodes them using native2unicode, and then parses the resulting string.
  • 'native2unicode' converts byte arrays to MATLAB character arrays based on the specified encoding (UTF-16LE, UTF-8, etc.)
  • This approach handles files with 16-bit encoding reliably, avoiding issues from fopen’s limited encoding support .
To know more about 'native2unicode' refer to the following official MathWorks documentation:
I hope this helps in resolving your query.

カテゴリ

Help Center および File ExchangeGet Started with MATLAB についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by