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

use*_*539 1 delphi

请问Rewrite现有文件的明确文件内容或它删除,然后创建一个新的?我的app.exe文件夹中有一个文本文件,我需要清除它.任何例子?

Ken*_*ite 5

从Delphi XE2文档中,重写主题- 阅读最后引用的段落:

创建一个新文件并将其打开.

在Delphi代码中,Rewrite创建一个名为F的新外部文件.

F是使用AssignFile与外部文件关联的任何文件类型的变量.RecSize是一个可选表达式,只有在F是无类型文件时才能指定.如果F是无类型文件,则RecSize指定要在数据传输中使用的记录大小.如果省略RecSize,则假定默认记录大小为128字节.

如果已存在具有相同名称的外部文件,则会删除该文件并在其位置创建新的空文件.

从相同的文档,链接在页面底部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;
Run Code Online (Sandbox Code Playgroud)

但是,您应该知道它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;
Run Code Online (Sandbox Code Playgroud)

注意你不能用TStrings; 这是一个抽象的类.你需要使用它的一个后代(TStringList是最经常使用的一个).