unit FileOpen;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, Grids;

type
  TForm1 = class(TForm)
    Edit1: TEdit;
    Button1: TButton;
    StringGrid1: TStringGrid;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

// BeginExample: FileOpen
// Routine: SysUtils.FileOpen

// BeginCode
{
This example requires a TEdit, a button and a string grid.
Enter the file name in the TEdit and click the button to open
that file.  Notice that the file cannot be read.  Remove the
fmOpenWrite and the fmShareDenyNone access and the string
grid loads fine.
}
procedure OpenForShare(const FileName: String);
var
  FileHandle : Integer;
  iFileLength: Integer;
  iBytesRead: Integer;
  Buffer: PAnsiChar;
  i: Integer;
begin
  FileHandle := SysUtils.FileOpen(FileName, fmOpenWrite or fmShareDenyNone or fmOpenRead);
  if FileHandle > 0 then
  begin
    try
      MessageDlg('Valid file handle.', mtInformation, [mbOk], 0);
      iFileLength := SysUtils.FileSeek(FileHandle,0,2);
      FileSeek(FileHandle, 0, 0);
      Buffer := PAnsiChar(System.AllocMem(iFileLength + 1));
      iBytesRead := SysUtils.FileRead(FileHandle, Buffer^, iFileLength);
      for i := 0 to iBytesRead-1 do
      begin
        Form1.StringGrid1.RowCount := Form1.StringGrid1.RowCount + 1;
        Form1.StringGrid1.Cells[1, i + 1] := Buffer[i];
        Form1.StringGrid1.Cells[2, i + 1] := IntToStr(Integer(Buffer[i]));
      end;
    finally
      FreeMem(Buffer);
    end;
  end
  else
    MessageDlg('Open error: FileHandle = negative DOS error code.', mtInformation, [mbOk], 0);
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  OpenForShare(Edit1.Text);
end;
// EndCode
// EndExample: FileOpen
end.
