2011-07-28 94 views
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; 
+2

你沒有提到你的Delphi版本。如果您使用的是D2009 +,則建議(由Delphi)使用流而不是「舊」Pascal文件方法,因爲這些方法不支持Unicode。 –

+3

而不是流,你可以使用'FileCreate()'來代替。 –

回答

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

謝謝...作品不錯... – user763539

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;