Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking File is Open in Delphi

Tags:

file-io

delphi

Is there a way to check if a file has been opened by ReWrite in Delphi?

Code would go something like this:

AssignFile(textfile, 'somefile.txt');
if not textFile.IsOpen then
   Rewrite(textFile);
like image 325
JamesSugrue Avatar asked Sep 26 '08 19:09

JamesSugrue


4 Answers

Try this:

function IsFileInUse(fName: string) : boolean;
var
  HFileRes: HFILE;
begin
  Result := False;
  if not FileExists(fName) then begin
    Exit;
  end;

  HFileRes := CreateFile(PChar(fName)
    ,GENERIC_READ or GENERIC_WRITE
    ,0
    ,nil
    ,OPEN_EXISTING
    ,FILE_ATTRIBUTE_NORMAL
    ,0);

  Result := (HFileRes = INVALID_HANDLE_VALUE);

  if not(Result) then begin
    CloseHandle(HFileRes);
  end;
end;
like image 43
JosephStyons Avatar answered Nov 03 '22 12:11

JosephStyons


You can get the filemode. (One moment, I'll create an example).

TTextRec(txt).Mode gives you the mode:

55216 = closed
55217 = open read
55218 = open write

fmClosed = $D7B0;
fmInput  = $D7B1;
fmOutput = $D7B2;
fmInOut  = $D7B3;

Search TTextRec in the system unit for more information.

like image 87
Toon Krijthe Avatar answered Nov 03 '22 12:11

Toon Krijthe


This works fine:

function IsOpen(const txt:TextFile):Boolean;
const
  fmTextOpenRead = 55217;
  fmTextOpenWrite = 55218;
begin
  Result := (TTextRec(txt).Mode = fmTextOpenRead) or (TTextRec(txt).Mode = fmTextOpenWrite)
end;
like image 9
Ramon Avatar answered Nov 03 '22 12:11

Ramon


I found it easier to keep a boolean variable as a companion; example: bFileIsOpen. Wherever the file is opened, set bFileIsOpen := true then, whenever you need to know if the file is open, just test this variable; example: if (bFileIsOpen) then Close(datafile);

like image 1
Mike Baran Avatar answered Nov 03 '22 10:11

Mike Baran