//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "FileOpen.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
	: TForm(Owner)
{
}
//---------------------------------------------------------------------------
#include <memory>       //for STL auto_ptr class

// 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.
*/
void __fastcall TForm1::Button1Click(TObject *Sender)
{
  int iFileHandle;
  int iFileLength;
  int iBytesRead;
  try
  {
	iFileHandle = FileOpen(Edit1->Text, fmOpenRead | fmOpenWrite | fmShareDenyNone);
	if (iFileHandle > 0) {
	  iFileLength = FileSeek(iFileHandle, 0, 2);
	  FileSeek(iFileHandle,0,0);
	  std::auto_ptr<AnsiChar> pszBuffer(new AnsiChar[iFileLength+1]);
	  iBytesRead = FileRead(iFileHandle, pszBuffer.get(), iFileLength);
      FileClose(iFileHandle);

	  for (int i = 0; i < iBytesRead; i++)
      {
		StringGrid1->RowCount += 1;
		StringGrid1->Cells[1][i+1] = pszBuffer.get()[i];
		StringGrid1->Cells[2][i+1] = IntToStr((int)pszBuffer.get()[i]);
      }
	}
	else
	{
	  Application->MessageBox(
		L"Can't perform one of the following file operations: Open, Seek, Read, Close.",
		L"File Error", IDOK);
	}
  }
  catch(...)
  {
	Application->MessageBox(
	  L"Can't perform one of the following file operations: Open, Seek, Read, Close.",
	  L"File Error", IDOK);
  }
}
// EndCode
// EndExample: FileOpen
//---------------------------------------------------------------------------
