如何判断是否assign了文件?

zoologist 2009-03-05 05:10:43
简单的程序:
procedure TForm1.Button1Click(Sender: TObject);
begin
if OpenDialog1.Execute then
begin
AssignFile(DealFile,Opendialog1.FileName);
Reset(DealFile);
end;
end;

我的问题是:如果我打开选择文件对话框后,并不选择任何文件。

是否有办法通过判断DealFile这个变量来确定是否assign了文件?

谢谢!
...全文
123 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
ahjoe 2009-03-05
  • 打赏
  • 举报
回复
楼上的同志很棒。
pathletboy 2009-03-05
  • 打赏
  • 举报
回复
用这个也行。2个结构差别在后面。

var
R: TFileRec absolute DealFile;
procedure TForm1.Button1Click(Sender: TObject);
begin
if OpenDialog1.Execute then
begin
AssignFile(DealFile,Opendialog1.FileName);
Reset(DealFile);
if R.Handle > 0 then
ShowMessage('文件已经打开');
end;
end;


2个结构

TFileRec = packed record (* must match the size the compiler generates: 332 bytes *)
Handle: Integer;
Mode: Word;
Flags: Word;
case Byte of
0: (RecSize: Cardinal); // files of record
1: (BufSize: Cardinal; // text files
BufPos: Cardinal;
BufEnd: Cardinal;
BufPtr: PChar;
OpenFunc: Pointer;
InOutFunc: Pointer;
FlushFunc: Pointer;
CloseFunc: Pointer;
UserData: array[1..32] of Byte;
Name: array[0..259] of Char; );
end;

{ Text file record structure used for Text files }
PTextBuf = ^TTextBuf;
TTextBuf = array[0..127] of Char;
TTextRec = packed record (* must match the size the compiler generates: 460 bytes *)
Handle: Integer; (* must overlay with TFileRec *)
Mode: Word;
Flags: Word;
BufSize: Cardinal;
BufPos: Cardinal;
BufEnd: Cardinal;
BufPtr: PChar;
OpenFunc: Pointer;
InOutFunc: Pointer;
FlushFunc: Pointer;
CloseFunc: Pointer;
UserData: array[1..32] of Byte;
Name: array[0..259] of Char;
Buffer: TTextBuf;
end;
ahjoe 2009-03-05
  • 打赏
  • 举报
回复
不好办了。DealFile是个结构体。
Delphi 5.0
sozeof(File) 得到 332
sozeof(TextFile) 得到 460

另外用个标志变量,与DealFile同步修改吧。
ljluck7687 2009-03-05
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 zoologist 的回复:]
if DealFile <>nil then //编译不通过,提示 类型不匹配

[/Quote]

不好意思

如果不通过打开对话框,那么只能通过置标志来判断了
pathletboy 2009-03-05
  • 打赏
  • 举报
回复

var
R: TTextRec absolute DealFile;
procedure TForm1.Button1Click(Sender: TObject);
begin
if OpenDialog1.Execute then
begin
AssignFile(DealFile,Opendialog1.FileName);
Reset(DealFile);
if R.Handle > 0 then
ShowMessage('文件已经打开');
end;
end
;
zoologist 2009-03-05
  • 打赏
  • 举报
回复
if DealFile <>nil then //编译不通过,提示 类型不匹配
ljluck7687 2009-03-05
  • 打赏
  • 举报
回复
if DealFile<>nil then
closefile(DealFile);

AssignFile(DealFile,FName);
Reset(DealFile);
bdmh 2009-03-05
  • 打赏
  • 举报
回复
已经打开的文件变量,如果再次使用AssignFile,就会出错,你可以再次AssignFile,捕获错误,^_^,方法有点...
zoologist 2009-03-05
  • 打赏
  • 举报
回复
这样的话,也并没有判断啊?

我的意思是要直接判断 DealFile,而不是通过OpenDialog
VIP_Rainbow 2009-03-05
  • 打赏
  • 举报
回复
procedure TForm1.Button1Click(Sender: TObject);
begin
if OpenDialog1.Execute then
begin
AssignFile(DealFile,Opendialog1.FileName);
Reset(DealFile);
end;
else
showmessage('请选择文件');
end;

5,388

社区成员

发帖
与我相关
我的任务
社区描述
Delphi 开发及应用
社区管理员
  • VCL组件开发及应用社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧