procedure ReplaceLines(
s: TStrings;
// Ersatzzeilen
fileName:
string;
// Name einer existierenden Textdatei
iStart: cardinal
// Zeilennummer, Beginn der Ersetzung, ab 0 gezählt
);
const
BUFSIZE = 32 * 1024;
var
fIn, fOut: TextFile;
fn, line:
string;
iCount, iStop: cardinal;
bufIn, bufOut:
array of byte;
begin
SetLength(fn, MAX_PATH);
if GetTempFileName('
.', '
TMP', 0, @fn[1]) = 0
then raise Exception.Create(SysErrorMessage(GetLastError))
else SetLength(fn, Pred(Pos(#0, fn)));
AssignFile(fIn, fileName);
Reset(fIn);
SetLength(bufIn, BUFSIZE);
SetTextBuf(fIn, bufIn[0]);
AssignFile(fOut, fn);
Rewrite(fOut);
SetLength(bufOut, BUFSIZE);
SetTextBuf(fOut, bufOut[0]);
iCount := 0;
iStop := iStart + s.Count;
while not Eof(fIn)
do
begin
ReadLn(fIn, line);
if (iCount < iStart)
or (iCount >= iStop)
then WriteLn(fOut, line)
else WriteLn(fOut, s[iCount - iStart]);
Inc(iCount);
end;
CloseFile(fIn);
CloseFile(fOut);
DeleteFile(fileName);
RenameFile(fn, fileName);
end;
procedure TDemoForm.ButtonClick(Sender: TObject);
const
fn = '
c:\daten\temp.txt';
begin
with Memo.Lines
do
begin
Clear;
Add('
123');
Add('
abc');
end;
// Zeilen 1 und 2 werden ersetzt, 0 bleibt erhalten
ReplaceLines(Memo.Lines, fn, 1);
end;