FileOpen (C++)

From RAD Studio Code Examples
Jump to: navigation, search

Description

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 to make the string grid load.

Note: File path is relative to the Debug directory

Code

void __fastcall TForm1::Button1Click(TObject *Sender)
{
  int iFileHandle;
  int iFileLength;
  int iBytesRead;
  PAnsiChar pszBuffer = 0;
  try
  {
	iFileHandle = FileOpen(Edit1->Text, fmOpenRead | fmOpenWrite | fmShareDenyNone);
	if (iFileHandle > 0) {
	  iFileLength = FileSeek(iFileHandle, 0, 2);
	  FileSeek(iFileHandle,0,0);
	  pszBuffer = new AnsiChar[iFileLength+1];
	  iBytesRead = FileRead(iFileHandle, pszBuffer, iFileLength);
	  FileClose(iFileHandle);

	  for (int i = 0; i < iBytesRead; i++)
	  {
		StringGrid1->RowCount += 1;
		StringGrid1->Cells[1][i+1] = pszBuffer[i];
		StringGrid1->Cells[2][i+1] = IntToStr((int)pszBuffer[i]);
	  }
	  delete [] pszBuffer;
	}
	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);
	delete [] pszBuffer;
  }
}

Uses