How to save classic Delphi string to disk (and read them back)?

前端 未结 4 632
走了就别回头了
走了就别回头了 2021-01-07 16:03

I want to achieve a very very basic task in Delphi: to save a string to disk and load it back. It seems trivial but I had problems doing this TWICE since I upgraded to IOUti

4条回答
  •  灰色年华
    2021-01-07 16:07

    Then the ReadAFile function should automagically detect the encoding and correctly read the string back.

    This is not possible. There exists files that are well-formed if interpreted as any text encoding. For instance see The Notepad file encoding problem, redux.

    This means that your goals are unattainable and that you need to change them.

    My advice is to do the following:

    • Pick a single encoding, UTF-8, and stick to it.
    • If the file does not exists, create it and write UTF-8 bytes to it.
    • If the file exists, open it, seek to the end, and append UTF-8 bytes.

    A text editor that does not understand UTF-8 is not worth supporting. If you feel inclined, include a UTF-8 BOM when you create the file. Use TEncoding.UTF8.GetBytes and TEncoding.UTF8.GetString to encode and decode.

提交回复
热议问题