tags:

views:

2513

answers:

3

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);
+9  A: 

You can get the filemode. (One moment, i 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.

Gamecat
A: 

I think your question should be, if you have a file handle in textfile, how do you determine whether it is open for ReWrite.

Of course this does not mean that the file can actually be written to, as it may be locked by other applications.

devio
+3  A: 

Try this:

function IsFileInUse(fName : string) : boolean;
var HFileRes : HFILE;
begin
  Result := False;
  if not FileExists(fName) then
    Exit;
  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
    CloseHandle(HFileRes);
end;
JosephStyons