开发者

Create multiple text files

what would be a neat way to create multiple *.txt files on application startup i.e check 开发者_运维知识库if they exist if not create them. I need to create about 10 text files. Will I have to do like this for every single file:

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;


If you only want to create the empty files (or rewrite the existing) with subsequently numbered file names, you might try something like this. The following examples use the CreateFile API function. But pay attention that several things may forbid your file creation attempts!

If you want to create (overwrite) them in all circumstances, use CREATE_ALWAYS disposition flag

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;

Or if you want to create the files only if they doesn't exist, use the CREATE_NEW disposition flag

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;


Something like this, perhaps:

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;


  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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜