Delphi 2009 - Cum scrii un fisier text cu caractere Unicode

Delphi 2009 - Cum scrii un fisier text cu caractere Unicode

Postby DarkByte » 20 Jul 2010, 11:00

Delphi 2009, desi (e primul Delphi care) suporta full Unicode, a pastrat TextFile-ul doar in varianta ANSI (ASCII).

Codul de mai jos scrie string-uri Unicode intr-un fisier text, folosind TFileStream. Daca fisierul nu exista, il creaza. Daca fisierul exista, dar nu are format Unicode, il va recrea (cu aceleasi date) in format Unicode.

Functia se comporta ca un WriteLn, dar daca parametrul aAddNewLine este pus pe False, se va comporta ca si Write.

  1. function StreamLog(aFilePath: String; aString: String;
  2.                    aAddNewLine: Boolean = True): Boolean;
  3. var
  4.   lFile: TFileStream;
  5.   lFileList: TStringList;
  6.   lEnc: Word;
  7. begin
  8.   Result := True;
  9.   try
  10.     try
  11.       ForceDirectories(ExtractFilePath(aFilePath));
  12.     except
  13.     end;
  14.  
  15.     if FileExists(aFilePath)
  16.       then lFile := TFileStream.Create(aFilePath, fmOpenReadWrite + fmShareCompat)
  17.       else lFile := TFileStream.Create(aFilePath, fmCreate + fmShareCompat);
  18.  
  19.     if aAddNewLine then
  20.       aString := aString + #13#10;
  21.  
  22.     if (lFile.Size = 0)
  23.       then aString := Chr($FEFF) + aString
  24.       else
  25.         begin
  26.           lFile.Read(lEnc, 2); // check file's encoding
  27.           if (lEnc <> $FEFF) then // if it's not Unicode
  28.             begin
  29.               lFile.Free; // close the file, just in case
  30.  
  31.               lFileList := TStringList.Create; // open it with StringList
  32.               lFileList.LoadFromFile(aFilePath); // load the file's content (assume it's text)
  33.               lFileList.SaveToFile(aFilePath, TEncoding.Unicode); // save it as unicode
  34.  
  35.               lFile := TFileStream.Create(aFilePath,
  36.                                 fmOpenReadWrite + fmShareCompat);
  37.               // continue adding the text
  38.             end;
  39.           lFile.Seek(0, soFromEnd);
  40.         end;
  41.     lFile.Write(aString[1], Length(aString) * SizeOf(Char));
  42.     lFile.Free;
  43.   except
  44.     Result := False;
  45.   end;
  46. end;


Bafta

2 points / 1 votes
User avatar
DarkByte
DWord
 
Joined: 29 Dec 2009
Points: 78

Return to Snippets

Who is online

Users browsing this forum: No registered users and 0 guests