gpt4 book ai didi

delphi-重写文件实际上做了什么?

转载 作者:行者123 更新时间:2023-12-02 15:28:36 24 4
gpt4 key购买 nike

Rewrite 是否会清除现有文件的文件内容,还是将其删除并创建一个新文件?我的 app.exe 文件夹中有一个文本文件,我需要清除该文件。有什么例子吗?

最佳答案

来自 Delphi XE2 文档,主题 Rewrite - 阅读最后引用的段落:

Creates a new file and opens it.

In Delphi code, Rewrite creates a new external file with the name assigned to F.

F is a variable of any file type associated with an external file using AssignFile. RecSize is an optional expression that can be specified only if F is an untyped file. If F is an untyped file, RecSize specifies the record size to be used in data transfers. If RecSize is omitted, a default record size of 128 bytes is assumed.

If an external file with the same name already exists, it is deleted and a new empty file is created in its place.

在同一文档中,页面底部的 System.Rewrite 链接已修改为使用您应用的文件夹:

procedure TForm1.Button1Click(Sender: TObject);
var
F: TextFile;
AppDir: string;
begin
// Instead of ParamStr(0), you can use Application.ExeName
// if you prefer
AppDir := ExtractFilePath(ParamStr(0));
AssignFile(F, AppDir + 'NEWFILE.$$$');
Rewrite(F); // default record size is 128 bytes
Writeln(F, 'Just created file with this text in it...');
CloseFile(F);
MessageDlg('NEWFILE.$$$ has been created in the ' + AppDir + ' directory.',
mtInformation, [mbOk], 0, mbOK);
end;

不过,您应该知道,Rewrite 已经过时并且不支持 Unicode。您应该使用更现代的方法来读取和写入文件,例如 TFileStreamTStringWriter (甚至是 TStringList 的简单解决方案)。

var
SL: TStringList;
AppDir: string;
begin
AppDir := ExtractFilePath(ParamStr(0));
SL := TStringList.Create;
try
SL.Add('Just created file with this text in it...');
// Add more lines here if needed, and then only save once
SL.SaveToFile(AppDir + 'NEWFILE.$$$');
MessageDlg('NEWFILE.$$$ has been created in the ' + AppDir + ' directory.',
mtInformation, [mbOk], 0, mbOK);
finally
SL.Free;
end;
end;

请注意,您不能使用TStrings;这是一个抽象类。您需要使用它的后代之一(TStringList 是最常用的)。

关于delphi-重写文件实际上做了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10867581/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com