在应用程序上创建多个* .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;
答案 0 :(得分: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;
答案 1 :(得分: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;
答案 2 :(得分: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);