0

什么是在应用程序启动时创建多个 *.txt 文件的好方法,即检查它们是否存在,如果不创建它们。我需要创建大约 10 个文本文件。我是否必须对每个文件都这样做:

var
  MyFile: textfile;
  ApplicationPath: string;
begin
  ApplicationPath := ExtractFileDir(Application.ExeName);
  if not FileExists(ApplicationPath + '\a1.txt') then
    begin
      AssignFile(MyFile, (ApplicationPath + '\a1.txt'));
      Rewrite(MyFile);
      Close(MyFile);
    end
  else 
    Abort;
end;
4

3 回答 3

4

如果您只想使用随后编号的文件名创建空文件(或重写现有文件),您可以尝试这样的事情。以下示例使用CreateFile API 函数。但请注意,有几件事可能会禁止您尝试创建文件!

如果您想在所有情况下创建(覆盖)它们,请使用 CREATE_ALWAYS 处置标志

procedure TForm1.Button1Click(Sender: TObject);
var
  I: Integer;
  Name: string;
  Path: string;
begin
  Path := ExtractFilePath(ParamStr(0));
  for I := 1 to 10 do
    begin
      Name := Path + 'a' + IntToStr(I) + '.txt';
      CloseHandle(CreateFile(PChar(Name), 0, 0, nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0));
    end;
end;

或者,如果您只想在文件不存在时创建文件,请使用 CREATE_NEW 处置标志

procedure TForm1.Button1Click(Sender: TObject);
var
  I: Integer;
  Name: string;
  Path: string;
begin
  Path := ExtractFilePath(ParamStr(0));
  for I := 1 to 10 do
    begin
      Name := Path + 'a' + IntToStr(I) + '.txt';
      CloseHandle(CreateFile(PChar(Name), 0, 0, nil, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, 0));
    end;
end;
于 2011-07-29T00:13:21.497 回答
3

像这样的东西,也许:

var
    ApplicationDir: string;
    I: Integer;
    F: TextFile;
begin
    ApplicationDir := ExtractFileDir(Application.ExeName);
    for I := 1 to 10 do
      begin
        Path := ApplicationDir + '\a' + IntToStr(I) + '.txt';
        if not FileExists(Path) then
          begin
            AssignFile(F, Path);
            Rewrite(F);
            Close(F);
          end
      end;
于 2011-07-28T23:50:36.080 回答
0
  procedure CreateFile(Directory: string; FileName: string; Text: string);
  var
    F: TextFile;
  begin
    try
      AssignFile(F, Directory + '\' + FileName);
      {$i-}
      Rewrite(F);
      {$i+}
      if IOResult = 0 then
      begin
         Writeln(F, Text);
      end;
    finally
      CloseFile(f);
    end;
  end;
  ...

  for i := 0 to 10 do
    CreateFile(Directory, Filename, Text);
于 2019-08-22T22:14:05.667 回答