Search code examples
delphidelphi-7

Save Hex value or UTF-16 [LE] inside a file in Delphi 7 [Error in using these codes]


Continuing from my previous question: How to save UTF-16 (Little Endian) and String value inside a file in Delphi 7?

When I use the following code from this answer:

uses
  Classes;
    
const
  BOM: WideChar = $FEFF;
var
  W: WideString;
  FS: TFileStream;
begin
  W := 'ᗿABC';
  FS := TFileStream.Create('text.txt', fmCreate);
  try
    FS.WriteBuffer(BOM, Sizeof(BOM));
    FS.WriteBuffer(PWideChar(W)^, Length(W) * Sizeof(WideChar));
  finally
    FS.Free;
  end;
end;

I have these problems:

  1. when I used this: W := 'ᗿABC'; my IDE showed W := '?ABC'; Can I fix this problem? Because [?] is not my goal

  2. When running the code, I get the error in the image:

image


Solution

    1. The code editor in Delphi 7 does not support Unicode characters very well, if at all. You really should stop using a 25-year-old compiler and upgrade.

      In any case, try this instead:

      W := #$15FF'ABC';
      

      Or, you may have to resort to something more like this:

      W := WideChar($15FF) + WideString('ABC');
      
    2. Try type-casting the integer value to WideChar:

      const
        BOM: WideChar = WideChar($FEFF);
      

      Otherwise, use Word instead of WideChar:

      const
        BOM: Word = $FEFF;