我正在努力用我的程序中的文本替换特定的文本行。到目前为止,我只是打开文件进行编辑...我尝试在互联网上搜索,但我能找到的最接近的是:http://wiki.freepascal.org/File_Handling_In_Pascal。该页面包含有关在现有文件中的一行下添加新文本并创建一个全新文件以添加文本,但不包含现有文件中特定行的所有内容...
var musicfile: TextFile;
AssignFile(musicfile, 'AlbumList.dat');
Append(musicfile);
WriteLn(musicfile, 'A text a want to replace line 5 with, but I dont know how to find line 5...');
Close(musicfile);
答案 0 :(得分:0)
您可以创建新文件并复制除要替换的行之外的所有行。像这样:
var musicfile: TextFile;
newfile: TextFile;
line: string[100]; // long enough to hold the longest line in the file
i: word; // counter for the lines
AssignFile(musicfile, 'AlbumList.dat');
AssignFile(newfile, 'AlbumList(1).dat'); // create new file
Reset(musicfile);
Rewrite(newfile); // open the new file for writing
i := 0 // we are at the 1st (index from zero) line
while not eof(musicfile) do begin
readln(musicfile, line); // read the line into a variable
if (i = 4) then // if we are at the 5th line, replace line
writeln(newfile, 'The string which should replace the 5th line')
else // just copy the line
writeln(newfile, line);
i := i + 1;
end;
Close(musicfile);
Close(newfile);
答案 1 :(得分:0)
作为一个不想创建新文件但想要重写旧文件的人,我使用了TStringList(在lazarus btw中进行了测试):
var fileStrList:TStringList;
begin
fileStrList:= TStringList.Create; //creating the TStringList
try
fileStrList.LoadFromFile('AlbumList.dat'); //Loading file into TStringList
fileStrList[4]:='Text you want to replace line 5 with'; //rewriting line 5
fileStrList.SaveToFile('AlbumList.dat'); //saving rewritted TStringList to file
finally
fileStrList.Free; //freeing the TStringList !don't forget about this!
end;
end;