【问题标题】:Create multiple text files创建多个文本文件
【发布时间】:2011-07-28 23:36:39
【问题描述】:

在应用程序上创建多个 *.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;

【问题讨论】:

  • 你没有提到你的 Delphi 版本。如果您使用的是 D2009+,建议您(Delphi)使用流而不是“旧”的 Pascal 文件方法,因为这些方法不支持 Unicode。
  • 你可以用FileCreate()代替流。

标签: file delphi application-start


【解决方案1】:

如果您只想创建带有随后编号的文件名的空文件(或重写现有文件),您可以尝试这样的操作。以下示例使用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;

【讨论】:

    【解决方案2】:

    可能是这样的:

    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;
    

    【讨论】:

      【解决方案3】:
        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);
      

      【讨论】:

        猜你喜欢
        • 2021-09-21
        • 2015-01-18
        • 1970-01-01
        • 2017-09-14
        • 1970-01-01
        • 2012-04-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多