2015-08-17

【Delphi】XE6 開啟/讀取 UTF8/unicode 純文字檔

資料來源 ----
unicode text file output differs between XE2 and Delphi 2009?

開啟/讀取 純文字檔的源碼:
預設開啟的文字檔格式為 ASCII

  1.  
  2. ...
  3. ...
  4. var
  5. txtFile: TextFile;
  6. str: string;
  7. begin
  8. AssignFile(txtFile, '檔名');
  9. Reset(txtFile);
  10. while not EOF(txtFile) do
  11. begin
  12. Readln(txtFile, str);
  13. end;
  14. end;
  15.  

AssignFile 有一個選擇性參數 CodePage,其資料型別為 Word,定義於 Winapi.Windows.pas,其對應值如下:

CP_ACP = 0;              { default to ANSI code page }
CP_OEMCP = 1;            { default to OEM  code page }
CP_MACCP = 2;            { default to MAC  code page }
CP_THREAD_ACP = 3;       { current thread's ANSI code page }
CP_SYMBOL = 42;          { SYMBOL translations }
CP_UTF7 = 65000;         { UTF-7 translation }
CP_UTF8 = 65001;         { UTF-8 translation }


若要開啟/讀取 UTF8 文字檔,則要加入 CP_UTF8 參數
  1.  
  2. ...
  3. ...
  4. var
  5. txtFile: TextFile;
  6. str: string;
  7. begin
  8. AssignFile(txtFile, '檔名', CP_UTF8);
  9. Reset(txtFile);
  10. while not EOF(txtFile) do
  11. begin
  12. Readln(txtFile, str);
  13. end;
  14. end;
  15.  

1 則留言:

  1. 這個問題搞了好久,突然看到前輩的文章,立馬加上 "CP_UTF8",立刻解決,太感謝了!

    回覆刪除