RAD Studio VCL Reference
ContentsIndex
PreviousUpNext
SysUtils.FileOpen Function

Opens a specified file using a specified access mode.

Pascal
function FileOpen(const FileName: string; Mode: LongWord): Integer;
C++
int FileOpen(const AnsiString FileName, LongWord Mode);

Use FileOpen to open a file and obtain a file handle. The access mode value is constructed by or-ing one of the fmOpen constants with one of the fmShare constants defined in File open mode constants. If the return value is 0 or greater, the function was successful and the value is the file handle of the opened file. A return value of -1 indicates that an error occurred. 

The Mode parameter consists of an open mode and (possibly) a share mode or'ed together. The open mode must be one of the following values:

Value 
Meaning 
Open the file for reading only.  
Open the file for writing only. Writing to the file completely replaces the current contents.  
Open the file to modify the current contents rather than replace them.  

The share mode must be one of the following values:

Value 
Meaning 
Sharing is compatible with the way FCBs are opened.  
Other applications can not open the file for any reason.  
Other applications can open the file for reading but not for writing.  
Other applications can open the file for writing but not for reading.  
No attempt is made to prevent other applications from reading from or writing to the file.  

Note: Use of the non-native Delphi language file handlers such as FileOpen is not encouraged. These routines map to system routines and return OS file handles, not normal Delphi file variables. These are low-level file access routines. For normal file operations use AssignFile, Rewrite, and Reset instead.
 

C++ Examples: 

 

/*
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);
  }
}
/*
The following example uses a button, a string grid, and an
Open dialog box on a form. When the button is clicked, the
user is prompted for a filename. When the user clicks OK,
the specified file is opened, read into a buffer, and closed.
Then the buffer is displayed in two columns of the string
grid. The first time you use this app, you should do a "Fill
Grid" and then "Write Grid to File".   Always use files
generated in this way to do a "Read File into Grid".
*/
// Read File to Grid

#include <memory>       //for STL auto_ptr class

void __fastcall TForm1::Button1Click(TObject *Sender)
{
  int iFileHandle;
  int iFileLength;
  int iBytesRead;
  int iLength;
  if (OpenDialog1->Execute())
  {
    try
    {
      iFileHandle = FileOpen(OpenDialog1->FileName, fmOpenRead);
      iFileLength = FileSeek(iFileHandle,0,2);
      FileSeek(iFileHandle,0,0);
      iBytesRead = FileRead(iFileHandle, reinterpret_cast<char *>(&(StringGrid1->ColCount)), 4);
      iBytesRead = FileRead(iFileHandle, reinterpret_cast<char *>(&(StringGrid1->RowCount)), 4);
      for (int x = 0; x < StringGrid1->ColCount; x++)
      {
        for (int y = 0; y < StringGrid1->RowCount; y++)
        {
          // Write out the length of each string, followed by the string itself.
          FileRead(iFileHandle, reinterpret_cast<char *>(&iLength), 4);
          std::auto_ptr<AnsiChar> pszBuffer(new AnsiChar[iLength + 1]);
          FileRead(iFileHandle, pszBuffer.get(), iLength);
          pszBuffer.get()[iLength] = 0;
          StringGrid1->Cells[x][y] = pszBuffer.get();
        }
      }
      FileClose(iFileHandle);
    }
    catch(...)
    {
#if defined(_DELPHI_STRING_UNICODE)
      Application->MessageBox(
        L"Can't perform one of the following file operations: Open, Seek, Read, Close.",
        L"File Error",
        IDOK);
#else
      Application->MessageBox(
        "Can't perform one of the following file operations: Open, Seek, Read, Close.",
        "File Error",
        IDOK);
#endif
    }
  }
}

// Write Grid into File

#include <dir.h>

void __fastcall TForm1::Button2Click(TObject *Sender)
{
  char szFileName[MAXFILE+4];
  int iFileHandle;
  int iLength;
  if (SaveDialog1->Execute())
  {
    if (FileExists(SaveDialog1->FileName))
    {
      fnsplit(AnsiString(SaveDialog1->FileName).c_str(), 0, 0, szFileName, 0);
      strcat(szFileName, ".BAK");
      RenameFile(SaveDialog1->FileName, szFileName);
    }
    iFileHandle = FileCreate(SaveDialog1->FileName);
    // Write out the number of rows and columns in the grid.
    FileWrite(iFileHandle, reinterpret_cast<char *>(&(StringGrid1->ColCount)), sizeof(StringGrid1->ColCount));
    FileWrite(iFileHandle, reinterpret_cast<char *>(&(StringGrid1->RowCount)), sizeof(StringGrid1->RowCount));
    for (int x=0;x<StringGrid1->ColCount;x++)
    {
      for (int y=0;y<StringGrid1->RowCount;y++)
      {
        // Write out the length of each string, followed by the string itself.
        iLength = StringGrid1->Cells[x][y].Length();
        FileWrite(iFileHandle, (AnsiChar *)&iLength, sizeof(iLength));
        FileWrite(iFileHandle, StringGrid1->Cells[x][y].t_str(), StringGrid1->Cells[x][y].Length());
      }
    }
    FileClose(iFileHandle);
  }
}
/*
The following example uses a button, a string grid, and an
Open dialog box on a form. When the button is clicked, the
user is prompted for a filename. When the user clicks OK,
the specified file is opened, read into a buffer, and closed.
Then the buffer is displayed in two columns of the string
grid. The first column contains the character values in the
buffer. The second column contains the numeric values of the
characters in the buffer.
*/

#include <memory>       //for STL auto_ptr class

void __fastcall TForm1::Button1Click(TObject *Sender)
{
  int iFileHandle;
  int iFileLength;
  int iBytesRead;
  char *pszBuffer;
  if (OpenDialog1->Execute())
  {
    try
    {
      iFileHandle = FileOpen(OpenDialog1->FileName, fmOpenRead);
      iFileLength = FileSeek(iFileHandle,0,2);
      FileSeek(iFileHandle,0,0);
//    pszBuffer = PChar(AllocMem(iFileLength+1));
      std::auto_ptr<char> pszBuffer(new char[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]);
      }
    }
    catch(...)
    {
      Application->MessageBox(
        L"Can't perform one of the following file operations: Open, Seek, Read, Close.",
        L"File Error", IDOK);
    }
  }
}

 

Delphi Examples: 

{
This example uses a file listbox and a regular listbox on a
form. The following routine scans through the files listed
in the file listbox and lists the sizes of any selected
files to the regular list box.  To exercise the error
condition create a file in the Debug directory, start this
application and then delete the file.  Now try to list the
size of the deleted file.  Set the MultiSelect and
ExtendedSelect properties on the FileListBox.
}
procedure TForm1.Button1Click(Sender: TObject);
var
  F: File;
  i, filehandle: Integer;
begin
  for i := 0 to (FileListBox1.Items.Count - 1) do begin
  try
    if FileListBox1.Selected[i] then 
    begin
      if not FileExists(FileListBox1.Items.Strings[i]) then
      begin
        MessageDlg('File: ' + FileListBox1.Items.Strings[i] +
                   ' not found', mtError, [mbOk], 0);
        Continue;
      end;
      filehandle:=  FileOpen(FileListBox1.Items.Strings[i], fmOpenWrite);
      if (filehandle = -1) then
      begin
        MessageDlg('File: ' + FileListBox1.Items.Strings[i] +
                   ' cannot be opened with access mode fmOpenWrite.', mtError, [mbOk], 0);
        Continue;
      end
      else
        FileClose(filehandle);

      AssignFile(F, FileListBox1.Items.Strings[i]);
      Reset(F, 1);
      ListBox1.Items.Add(
        FileListBox1.Items.Strings[i] + ': ' + IntToStr(FileSize(F)));
      CloseFile(F);
    end;
   finally
   { do something here }
   end;
  end;
end;
{
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;
{
The following example uses a button, a string grid, and an
Open dialog box on a form. When the button is clicked, the
user is prompted for a filename. When the user clicks OK,
the specified file is opened, read into a buffer, and closed.
Then the buffer is displayed in two columns of the string
grid. The first column contains the character values in the
buffer. The second column contains the numeric values of the
characters in the buffer.
} 
procedure TForm1.Button1Click(Sender: TObject);
var
  iFileHandle: Integer;
  iFileLength: Integer;
  iBytesRead: Integer;
  Buffer: PAnsiChar;
  i: Integer;
begin
  if OpenDialog1.Execute then
  begin
    try
      iFileHandle := SysUtils.FileOpen(OpenDialog1.FileName, fmOpenRead);
      iFileLength := SysUtils.FileSeek(iFileHandle,0,2);
      FileSeek(iFileHandle,0,0);
      Buffer := System.AllocMem(iFileLength + 1);
      iBytesRead := SysUtils.FileRead(iFileHandle, Buffer^, iFileLength);
      FileClose(iFileHandle);
      for i := 0 to iBytesRead-1 do
      begin
        StringGrid1.RowCount := StringGrid1.RowCount + 1;
        StringGrid1.Cells[1,i+1] := Buffer[i];
        StringGrid1.Cells[2,i+1] := IntToStr(Integer(Buffer[i]));
      end;
    finally
      FreeMem(Buffer);
    end;
  end;
end;
{
The following example uses a button, a string grid, and an
Open dialog box on a form. When the button is clicked, the
user is prompted for a filename. When the user clicks OK,
the specified file is opened, read into a buffer, and closed.
Then the buffer is displayed in two columns of the string
grid. The first column contains the character values in the
buffer. The second column contains the numeric values of the
characters in the buffer.
}
// Read File to Grid
procedure TForm1.Button1Click(Sender: TObject);
var
  iFileHandle: Integer;
  iFileLength: Integer;
  iBytesRead: Integer;
  Buffer: PAnsiChar;
  X, Y, I: Integer;
  StringLen, colcnt, rowcnt: Integer;
  cellString: String;
begin
  if OpenDialog1.Execute then
  begin
    try
      iFileHandle := SysUtils.FileOpen(OpenDialog1.FileName, fmOpenRead);
      iFileLength := SysUtils.FileSeek(iFileHandle,0,2);
      FileSeek(iFileHandle,0,0);
//      Buffer := PChar(System.AllocMem(iFileLength + 1));
//      iBytesRead := SysUtils.FileRead(iFileHandle, Buffer^, iFileLength);
//      FileClose(iFileHandle);
//      iFileHandle := SysUtils.FileOpen(OpenDialog1.FileName, fmOpenRead);
//      iFileLength := SysUtils.FileSeek(iFileHandle,0,2);
//      FileSeek(iFileHandle,0,0);
      colcnt := StringGrid1.ColCount;
      iBytesRead := SysUtils.FileRead(
        iFileHandle,
        colcnt,
        4);  // 4 because it's an integer
      rowcnt := StringGrid1.RowCount;
      iBytesRead := SysUtils.FileRead(
        iFileHandle,
        rowcnt,
        4);  // 4 because it's an integer
    for X := 0 to StringGrid1.ColCount - 1 do
    begin
      for Y := 0 to StringGrid1.RowCount - 1 do
      begin
        try
          iBytesRead := SysUtils.FileRead(iFileHandle, StringLen, 4);  // 4 because it's an integer
          Buffer := System.AllocMem(StringLen + 1);
//          GetMem(Buffer, StringLen); { allocate the buffer }
          iBytesRead := SysUtils.FileRead(iFileHandle, Buffer^, StringLen);
//          for I := 1 to StringLen do
//            cellString[I] := Buffer[I - 1];
          StringGrid1.Cells[X,Y] := AnsiString(Buffer);
        finally
          FreeMem(Buffer);
        end;
      end;
    end;
    finally
      FileClose(iFileHandle);
    end;
  end;
end;

// Write Grid into File
procedure TForm1.Button2Click(Sender: TObject);
var
  BackupName: string;
  FileHandle: Integer;
  StringLen: Integer;
  X, Y, I: Integer;
  colCountLength, rowCountLength: Integer;
  Buffer: PAnsiChar;
  cellString: AnsiString;
begin
  if SaveDialog1.Execute then
  begin
    if FileExists(SaveDialog1.FileName) then
    begin
      BackupName := SysUtils.ExtractFileName(SaveDialog1.FileName);
      BackupName := ChangeFileExt(BackupName, '.BAK');
      if not RenameFile(SaveDialog1.FileName, BackupName) then
        raise Exception.Create('Unable to create backup file.');
    end;
    FileHandle := FileCreate(SaveDialog1.FileName);
    { Write out the number of rows and columns in the grid. }
    colCountLength := SizeOf(StringGrid1.ColCount);
    FileWrite(FileHandle, 
      PAnsiChar(StringGrid1.ColCount), colCountLength);
    rowCountLength := SizeOf(StringGrid1.RowCount);
    FileWrite(FileHandle,
      PAnsiChar(StringGrid1.RowCount), rowCountLength);
    for X := 0 to StringGrid1.ColCount - 1 do
    begin
      for Y := 0 to StringGrid1.RowCount - 1 do
      begin
        try
          { Write out the length of each string, followed by the string itself. }
          StringLen := Length(StringGrid1.Cells[X,Y]);
          FileWrite(FileHandle, PChar(StringLen), SizeOf(StringLen));
          GetMem(Buffer, StringLen); { allocate the buffer }
          cellString := StringGrid1.Cells[X,Y];
          for I := 1 to StringLen do
             Buffer[I - 1] := cellString[I];
          FileWrite(FileHandle, Buffer^, StringLen);
        finally
          FreeMem(Buffer, StringLen);
        end;
      end;
    end;
    FileClose(FileHandle);
  end;
end;

 

Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!