Mega Code Archive

 
Categories / Delphi / Files
 

How to open a Delphi text file fmShareDenyNone

Title: How to open a Delphi text file fmShareDenyNone? Question: Delphis system.filemode variable controls only the mode of binary files. For text files this variable is ignored. I wanted to open a file in text mode even an other process keeps it open for writing (unless it denies read), but I did not want to alter the assembler code in the VCL. Answer: // Important: The following code was only tested with Delphi 5 Implementation Uses Windows, SysUtils, SysConst; procedure OpenReadText(var f:Text;SwitchIminus:Boolean); // Opening a text file that might be open for write // Input // f: a text file that was prepared with AssignFile // SwitchIminus: set true if you want {$-} style processing, // with no exceptions begin try // try the standard way i.e. generic_read, file_share_read // this is important to further prepare the TextRect items // If the file is not open for write, its done, we need reset // to assign the imput function to TTextRec(f).InoutFunc Reset(f); except with TTextRec(f) do begin // else we try generic_read, file_share_read or file_share_write handle:=FileOpen(Name,fmShareDenyNone); if dword(handle)=invalid_handle_value then begin if SwitchIminus then SetInOutRes(GetLastError) else raise EInOutError.CreateResFmt(@SInOutError, [GetLastError]); end; mode:=fmInput; BufPos:=0; BufEnd:=0; end; end; end{OpenReadText};