Delphi文件管理操作实例

1.AssignFile 过程
关联一个外部文件名到一个文件变量上。
单元
System

语法
procedure AssignFile(var F; FileName: string);

描述
调用AssignFile来初始化Delphi代码中的文件变量。F是一个任何文件类型的文件变量。FileName是一个字符串类型的表达式,或者,如果扩展的语法激活的话,是PChar类型的表达式。
调用AssignFile之后,F就和外部文件关联起来直到F被关闭。所有在文件变量F上的更多的操作都会操作在名为Filename的外部文件上。
FileName参数为空时,AssignFile会将F和标准输入或标准输出文件关联起来。如果赋予一个空名字,在调用了Reset(F)之后,F将引用标准输入文件,而在调用了Rewrite(F)之后,F将引用标准输出文件。
不要在已经打开的文件变量上使用AssignFile
注意:为了避免范围冲突,AssignFile 代替了在早期版本的Delphi产品中可用的Assign过程。然而为了向后兼容Assign仍然是可用的。
示例
var
F: TextFile;
S: string;
begin
if OpenDialog1.Execute then { Display Open dialog box }
begin
AssignFile(F, OpenDialog1.FileName); { File selected in dialog }
Reset(F);
Readln(F, S); { Read first line of file }
Edit1.Text := S; { Put string in a TEdit control }
CloseFile(F);
end;
end;

2.ChDir 过程
改变当前目录

单元
System

语法
procedure ChDir(const S: string); overload;
procedure ChDir(P: PChar); overload;

描述
ChDir 会将当前目录改变为由SP指定的路径。如果这个操作失败,异常EInOutError将会引发。
Windows上,路径可以包含驱动器指示符(drive specifier),而这将导致当前的驱动盘同时改变。
注意:在Delphi中,{$I+} 使用异常来处理运行时错误。当使用{$I-}时,要使用IOResult来检查I/O错误。
示例
begin
{$I-}
{ Change to directory specified in Edit1 }
ChDir(Edit1.Text);
if IOResult <> 0 then
MessageDlg('Cannot find directory', mtWarning, [mbOk], 0);
end;

3.CloseFile 过程
终止文件变量和外部磁盘文件之间的关联

单元
System

语法
procedure CloseFile(var F);

描述
由于命名冲突,CloseFile代替了Close过程。使用CloseFile过程而不是Close来终止文件变量和外部磁盘文件之间的关联。
F是一个使用ResetRewriteAppend打开的任何文件类型的文件变量。和F关联的外部文件会完全地更新然后关闭并释放文件句柄便于重用。
注意:{$I+} 使用异常来处理运行时错误。当使用{$I-}时,要使用IOResult检查I/O 错误。

4.CreateDir 函数
创建一个新目录
单元
SysUtils
语法
function CreateDir(const Dir: string): Boolean;
描述
CreateDir 创建一个新目录。如果新目录成功创建,则返回值为true,或者如果出现错误则返回值为false
示例
下面的例子会创建目录'C:\temp',如果目录不存在的话。

uses FileCtrl;

procedure TForm1.Button1Click(Sender: TObject);
begin
if not DirectoryExists('c:\temp') then
if not CreateDir('C:\temp') then
raise Exception.Create('Cannot create c:\temp');
end;

5.DeleteFile 函数
从删除一个磁盘文件
单元
SysUtils
语法
function DeleteFile(const FileName: string): Boolean;
描述
DeleteFile 删除磁盘上由 FileName 命名的文件。如果文件不能被删除或者文件不存在,函数将返回false
示例

if FileExists(FileName) then
if MessageDlg('Do you really want to delete ' + ExtractFileName(FileName) + '?'), mtConfirmation, [mbYes, mbNo], 0, mbNo) = IDYes then
DeleteFile(FileName);

6.DirectoryExists 函数
确定指定的目录是否存在
单元
SysUtils
语法
function DirectoryExists(const Directory: string): Boolean;
描述
调用 DirectoryExists 来确定由Directory参数指定的目录是否存在。如果目录存在,函数返回true。如果目录不存在,函数返回false
如果输入的是全称路径名(full path name)DirectoryExists 会沿着指定的路径查找目录。否则Directory参数会被认为是当前目录的相对路径。
FileCtrl 单元(仅用于Windows) 同样包含一个 DirectoryExists 函数。然而,FileCtrl 版本是不赞成的,SysUtils 版本是首选的,即使代码不需要跨平台(However, the FileCtrl version is deprecated, and the SysUtils version preferred, even if the code does not need to be cross-platform)

7.DiskFree 函数
返回指定盘符上空闲的字节数
单元
SysUtils
语法
function DiskFree(Drive: Byte): Int64;
描述
DiskFree 返回指定驱动盘()的空闲字节数,其中 0 = 当前盘, 1 = A 2 = B,等等。如果驱动盘数字无效,DiskFree 返回-1
注意:DiskFree

仅在Windows上可用。
示例
var
S: string;
AmtFree: Int64;
Total: Int64;
begin
AmtFree := DiskFree(0);
Total := DiskSize(0);
S := IntToStr(AmtFree div Total) + 'percent of the space on drive 0 is free: ' (AmtFree div 1024) + ' Kbytes free. ';
Label1.Caption := S;
end;

8.DiskSize 函数
返回指定盘符的字节大小
单元
SysUtils
语法
function DiskSize(Drive: Byte): Int64;
描述
DiskSize 返回指定驱动盘的字节大小,其中 0 = 当前盘,1 = A 2 = B 等等。如果驱动盘数字无效,DiskSize返回-1
注意:DiskSize 仅在Windows上可用。

9.文件模式常量(File mode constants)
文件模式常量用于打开和关闭磁盘文件
单元
System
语法
const fmClosed = $D7B0; // closed file
const fmInput = $D7B1; // reset file (TTextRec)
const fmOutput = $D7B2; // rewritten file (TTextRec)
const fmInOut = $D7B3; // reset or rewritten file (TFileRec)
const fmCRLF = $8 // DOS-style EoL and EoF markers (TTextRec)
const fmMask = $D7B3; // mask out fmCRLF flag (TTextRec)
描述 当打开和关闭磁盘文件时,使用文件模式常量。这些常量主要用在这样的Delphi代码中,TFileRecTTextRecMode字段包含这些值中的某个值(These constants are used primarily in Delphi code, where the Mode field of TFileRec and TTextRec contain one of these values.)

10.文件名称常量(File name constants)
文件名称常量用于以平台中立的方式表达文件名称。
单元
SysUtils
语法
const
PathDelim = {$IFDEF MSWINDOWS} '\'; {$ELSE} '/'; {$ENDIF}
DriveDelim = {$IFDEF MSWINDOWS} ':'; {$ELSE} ''; {$ENDIF}
PathSep = {$IFDEF MSWINDOWS} ';'; {$ELSE} ':'; {$ENDIF}
描述
文件名称常量指定了在WindowsLinux中不同的的定界符和分隔符(delimiter and separator)

11.文件打开模式常量(File open mode constants)
打开打开模式常量用于控制对文件或流的访问模式。
单元
SysUtils
语法
On Windows:
const
fmCreate = $FFFF;
fmOpenRead = $0000;
fmOpenWrite = $0001;
fmOpenReadWrite = $0002;

fmShareCompat = $0000 platform;
fmShareExclusive = $0010;
fmShareDenyWrite = $0020;
fmShareDenyRead = $0030 platform;
fmShareDenyNone = $0040;

On Linux:
const
fmOpenRead = O_RDONLY;
fmOpenWrite = O_WRONLY;
fmOpenReadWrite = O_RDWR;
fmShareExclusive = $0010;
fmShareDenyWrite = $0020;
fmShareDenyNone = $0030;

描述
当文件或流被打开时,文件打开模式常量用于控制文件或流能够如何共享。
TFileStream构造函数有一个Mode参数,你能够设置为这些常量中的一个:
Constant Definition

fmCreate 如果文件存在,那么将打开用于写访问,否则会创建新文件。其他的常量都声明在 SysUtils 单元,而这个常量声明在 Classes 单元中
fmOpenRead 仅以读访问方式打开
fmOpenWrite 仅以写访问方式打开
fmOpenReadWrite 以读写访问方式打开
fmShareCompat FCB打开的方法兼容。不要在跨平台应用程序中使用这个模式
fmShareExclusive 读写访问被拒绝
fmShareDenyWrite 写访问被拒绝
fmShareDenyRead 读访问被拒绝。不要在跨平台应用程序中使用这个模式
fmShareDenyNone 允许其他代码进行完全的访问

12.FileAccessRights 变量
当应用程序被调用时指向特殊的命令行参数。
单元
System
语法
var FileAccessRights: Integer platform;
描述
Windows 中,FileAccessRights 变量被忽略。
Linux 中,每个文件都有一组许可位(permission bits)控制着对文件的访问。当创建新文件时,FileAccessRights 指定了一组默认的许可标记来使用。当你没有显式指定要使用的许可位时,FileCreate 方法使用 FileAccessRights 来设置它创建的文件的访问权力。


13.FileAge 函数
返回文件的OS时间戳(Returns the OS timestamp of a file.)
单元
SysUtils
语法
function FileAge(const FileName: string): Integer;
描述
调用 FileAge 来获得由 FileNameto 指定的文件的 OS 时间戳。返回值可以使用 FileDateToDateTime函数转换为TDateTime对象。如果文件不存在返回值为 -1
Linux中,-1 是一个有效的时间戳。可使用 FileExists 核实文件不存在。
示例
下面的代码将一个文件的属性读入一组变量中,并在文件属性对话框中设置检查框以表现当前的属性,然后执行对话框。如果用户改变并接受对话框的设置,代码将设置文件属性以匹配改变的设置:
procedure TFMForm.Properties1Click(Sender: TObject);
var

Attributes, NewAttributes: Word;
begin
with FileAttrForm do
begin
FileDirName.Caption := FileList.Items[FileList.ItemIndex];
{ set box caption }
PathName.Caption := FileList.Directory;
{ show directory name }
ChangeDate.Caption :=
DateTimeToStr(FileDateToDateTime(FileAge(FileList.FileName)));
Attributes := FileGetAttr(FileDirName.Caption);
{ read file attributes }
ReadOnly.Checked := (Attributes and SysUtils.faReadOnly) = faReadOnly;
Archive.Checked := (Attributes and faArchive) = faArchive;
System.Checked := (Attributes and faSysFile) = faSysFile;
Hidden.Checked := (Attributes and faHidden) = faHidden;
if ShowModal <> id_Cancel then { execute dialog box }
begin
NewAttributes := Attributes;
{ start with original attributes }
if ReadOnly.Checked then
NewAttributes := NewAttributes or SysUtils.faReadOnly
else
NewAttributes := NewAttributes and not SysUtils.faReadOnly;
if Archive.Checked then
NewAttributes := NewAttributes or faArchive
else
NewAttributes := NewAttributes and not faArchive;
if System.Checked then
NewAttributes := NewAttributes or faSysFile
else
NewAttributes := NewAttributes and not faSysFile;
if Hidden.Checked then
NewAttributes := NewAttributes or faHidden
else
NewAttributes := NewAttributes and not faHidden;
if NewAttributes <> Attributes then { if anything changed... }
FileSetAttr(FileDirName.Caption, NewAttributes);
{ ...write the new values }
end;
end;
end;

14.FileClose 过程
关闭指定的文件
单元
SysUtils
语法
procedure FileClose(Handle: Integer);
描述
FileClose 关闭给定文件句柄的文件。句柄在文件使用FileOpenFileCreate打开时获得。
当和Delphi语言的文件变量一起使用时,应使用 CloseFile 过程代替。
示例
下面的例子使用了一个按钮,一个字符串栅格和一个保存对话框在窗体上。单击按钮后,用户将被提示输入文件名。当用户单OK后,字符串栅格的内容将被写到指定的文件中。附加的信息同样被写到文件中,以便文件能够使用FileRead函数容易地读取。
procedure TForm1.Button1Click(Sender: TObject);
var
BackupName: string;
FileHandle: Integer;
StringLen: Integer;
X: Integer;
Y: Integer;
begin
if SaveDialog1.Execute then
begin
if FileExists(SaveDialog1.FileName) then
begin
BackupName := ExtractFileName(SaveDialog1.FileName);
BackupName := ChangeFileExt(BackupName, '.BAK');
if not RenameFile(SaveDialog1.FileName, BackupName) then
raise Exception.Create('Unable to create backup file.');
end;
FileHandle := FileCreate(SaveDialog1.FileName);
{ Write out the number of rows and columns in the grid. }
FileWrite(FileHandle,
StringGrid1.ColCount, SizeOf(StringGrid1.ColCount));
FileWrite(FileHandle,
StringGrid1.RowCount, SizeOf(StringGrid1.RowCount));
for X := 0 to StringGrid1.ColCount - 1 do
begin
for Y := 0 to StringGrid1.RowCount - 1 do
begin
{ Write out the length of each string, followed by the string itself. }
StringLen := Length(StringGrid1.Cells[X,Y]);
FileWrite(FileHandle, StringLen, SizeOf(StringLen));
FileWrite(FileHandle,
StringGrid1.Cells[X,Y], Length(StringGrid1.Cells[X,Y]);
end;
end;
FileClose(FileHandle);
end;
end;


15.FileCreate 函数
创建一个新文件
单元
SysUtils
语法
function FileCreate(const FileName: string): Integer; overload;
function FileCreate(const FileName: string; Rights: Integer): Integer; overload;

描述
FileCreate 用指定的名称创建新文件。如果返回值是正数,说明函数成功而且值是新文件的句柄。返回值是-1说明有错误发生。
Windows中,FileAccessRights 变量和 Rights 参数被忽略。

 

转载于:https://www.cnblogs.com/seahorse/archive/2009/06/18/1505624.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值