I had some code before I switched to Unicode and Delphi 2009, which attached text in a line to a text file:
procedure AppendToLogFile(S: string); // this function adds our log line to our shared log file // Doing it this way allows Wordpad to open it at the same time. var F, C1 : dword; begin if LogFileName <> '' then begin F := CreateFileA(Pchar(LogFileName), GENERIC_READ or GENERIC_WRITE, 0, nil, OPEN_ALWAYS, 0, 0); if F <> 0 then begin SetFilePointer(F, 0, nil, FILE_END); S := S +
But CreateFileA and WriteFile are binary processors and are not suitable for Unicode .
I need to get something that needs to be done in Delphi 2009 and be able to handle Unicode.
The reason I open and write and then close the file for each line is simply because other programs (such as WordPad) can open the file and read it while writing a log.
I experimented with TFileStream and TextWriter, but the documentation for them is very small and a few examples.
In particular, I'm not sure if they are suitable for this constant opening and closing of a file. Also, I'm not sure if they can make the file readable while it is open for writing.
Does anyone know how I can do this in Delphi 2009 or later?
Output:
Ryan's answer was the simplest, and the one that led me to my decision. With his solution, you also need to write a specification and convert the string to UTF8 (as in my comment on his answer), and then it worked fine.
But then I took another step and explored TStreamWriter. This is the equivalent of a .NET function with the same name. It understands Unicode and provides very clean code.
My last code is:
procedure AppendToLogFile(S: string); // this function adds our log line to our shared log file // Doing it this way allows Wordpad to open it at the same time. var F: TStreamWriter; begin if LogFileName <> '' then begin F := TStreamWriter.Create(LogFileName, true, TEncoding.UTF8); try F.WriteLine(S); finally F.Free; end; end;
Finally, another aspect that I discovered is that you add a lot of lines (for example, 1000 or more), then adding to the file takes longer and longer, and it becomes quite inefficient.
So, I ended up not re-creating or releasing the LogFile every time. Instead, I keep it open, and then it is very fast. The only thing I can not do is allow the file to be viewed with notepad during its creation.