Recent

Author Topic: how to create a text file with utf-8 encoding  (Read 6113 times)

fxc

  • Newbie
  • Posts: 5
how to create a text file with utf-8 encoding
« on: February 11, 2016, 04:28:12 pm »
Hi
i tried with assignfile() and rewrite() , but the result file is asci
are there some compiler hints to switch to unicode api ?

thanks

 

Jonas Maebe

  • Hero Member
  • *****
  • Posts: 1070
Re: how to create a text file with utf-8 encoding
« Reply #1 on: February 11, 2016, 04:38:48 pm »
The format in which data is written to a file is unrelated to any kind of API. It's all just bytes as far as the operating system is concerned.

If you have a text file, you can change the code page of the written data using the http://www.freepascal.org/docs-html/rtl/system/settextcodepage.html function. Passing CP_UTF8 will result in all data written to it to be converted to UTF-8.

fxc

  • Newbie
  • Posts: 5
Re: how to create a text file with utf-8 encoding
« Reply #2 on: February 11, 2016, 05:22:56 pm »
thanks Jonas , this function (SetTextCodePage) is what was missing  , now the resulting file contain correct text

this is for text file , what if i want to write utf-8 text to a binary file ?

Jonas Maebe

  • Hero Member
  • *****
  • Posts: 1070
Re: how to create a text file with utf-8 encoding
« Reply #3 on: February 11, 2016, 06:12:08 pm »
this is for text file , what if i want to write utf-8 text to a binary file ?
A binary file is just arbitrary bytes. If the bytes you write represent UTF-8 text, then your file will contain UTF-8-encoded text.

fxc

  • Newbie
  • Posts: 5
Re: how to create a text file with utf-8 encoding
« Reply #4 on: February 11, 2016, 08:30:12 pm »
thanks again jonas , now i've a clear understanding

nk

  • Newbie
  • Posts: 2
Re: how to create a text file with utf-8 encoding
« Reply #5 on: March 14, 2025, 08:54:35 pm »
You could use assignfile or TStringList :

Code: Pascal  [Select][+][-]
  1. program project1;
  2.  
  3. uses
  4.   Classes,
  5.   SysUtils;
  6.  
  7. var
  8.   F: Text;
  9.   SL: TStringList;
  10. begin
  11.  
  12.  
  13.   // option 1
  14.   try
  15.     assignfile(f, 'text1.txt', CP_UTF8);
  16.     Rewrite(f);
  17.     writeln(f, 'Привет мир');
  18.     writeln(f, 'Möhren');
  19.   finally
  20.     Close(f);
  21.   end;
  22.  
  23.   // option 2
  24.   SL := TStringList.Create;
  25.   try
  26.     SL.Add('∫cos(x)dx = sin(x) + C');
  27.     SL.Add('¬(a ∧ b) ⇔ ¬a ∨ ¬b');
  28.     SL.Add('Привет мир');
  29.     SL.Add('Möhren');
  30.     SL.SaveToFile('text2.txt', TEncoding.UTF8);
  31.   finally
  32.     SL.Free;
  33.   end;
  34.  
  35.  
  36. end.
  37.  

 

TinyPortal © 2005-2018