For Delphi 10.1 (Berlin) or newer, the best solution is described in Uwe's answer.
For older Delphi versions, I found a solution by creating a child class of TStringList
and overriding the TStrings.GetTextStr
virtual function but I will be glad to know if there is a better solution or if someone else found something wrong in my solution
Interface:
uses
Classes;
type
TMyStringList = class(TStringList)
private
FIncludeLastLineBreakInText : Boolean;
protected
function GetTextStr: string; override;
public
constructor Create(AIncludeLastLineBreakInText : Boolean = False); overload;
property IncludeLastLineBreakInText : Boolean read FIncludeLastLineBreakInText write FIncludeLastLineBreakInText;
end;
Implementation:
uses
StrUtils;
constructor TMyStringList.Create(AIncludeLastLineBreakInText : Boolean = False);
begin
inherited Create;
FIncludeLastLineBreakInText := AIncludeLastLineBreakInText;
end;
function TMyStringList.GetTextStr: string;
begin
Result := inherited;
if(not IncludeLastLineBreakInText) and EndsStr(LineBreak, Result)
then SetLength(Result, Length(Result) - Length(LineBreak));
end;
Example:
procedure TForm1.Button1Click(Sender: TObject);
var
Lines : TStrings;
begin
Lines := TMyStringList.Create();
try
Lines.LoadFromFile('.\input.txt');
Lines.SaveToFile('.\output.txt');
finally
Lines.Free;
end;
end;
\n
character and the function adds the\n
to the file? Or does the function literally add a\n
right after an existing\n
at the end of file? POSIX requires text files to have all their lines terminated by a\n
, just fyi. Lots of software was written to follow some standards so that's why a lot of editors will add the missing terminating\n
when you save files by default (e.g.vim
, IDEs etc all by default make your files POSIX-compliant.) – Losel