delphi 内存映射读取文件内存  
官方Delphi 学习QQ群: 682628230(三千人)
频道

delphi 内存映射读取文件内存


function TForm1.MMFileToString(const AFilename: string): string;

var

  hFile: THandle;

  hFileMap: THandle;

  hiSize: DWORD;

  loSize: DWORD;

  text: string;

  view: pointer;

begin

  Result := '';

  if AFilename = '' then

    Exit;

  if not FileExists(AFilename) then

    Exit;

  {Open the file}

  hFile := CreateFile(

    PChar(AFilename), GENERIC_READ, FILE_SHARE_READ, nil,

    OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0

  );

  if hFile <> INVALID_HANDLE_VALUE then

  begin

    loSize := GetFileSize(hFile, @hiSize);

    {File was opened successfully, now map it:}

    hFileMap := CreateFileMapping(

      hFile, nil, PAGE_READONLY, hiSize, loSize, 'TextForString'

    );

    if (hFileMap <> 0) then

    begin

      if (GetLastError() = ERROR_ALREADY_EXISTS) then

      begin

        MessageDlg(

          'Mapping already exists - not created.', mtWarning, [mbOk], 0

        );

        CloseHandle(hFileMap)

      end

      else

      begin

        try

          {File mapped successfully, now map a view of the file into the

          address space:}

          view := MapViewOfFile(hFileMap, FILE_MAP_READ, 0, 0, 0);

          if (view <> nil) then

          begin {View mapped successfully}

            {Close file handle - as long is view is open it will persist}

            CloseHandle(hFile);

            SetLength(Result, loSize);

            

            Move(view^, Result[1], loSize);

          end

          else

            MessageDlg(

              'Unable to map view of file. ' + SysErrorMessage(GetLastError),

              mtWarning, [mbOk], 0

            );

        finally

          UnmapViewOfFile(view);  {Close view}

          CloseHandle(hFileMap);  {Close mapping}

        end

      end

    end

    else

    begin

      MessageDlg(

        'Unable to create file mapping. ' + SysErrorMessage(GetLastError),

        mtWarning, [mbOk], 0

      );

    end;

  end

  else

  begin

    MessageDlg(

      'Unable to open file. ' + SysErrorMessage(GetLastError),

      mtWarning, [mbOk], 0

    );

  end;

end;



推荐分享
图文皆来源于网络,内容仅做公益性分享,版权归原作者所有,如有侵权请告知删除!
 

Copyright © 2014 DelphiW.com 开发 源码 文档 技巧 All Rights Reserved
晋ICP备14006235号-8 晋公网安备 14108102000087号

执行时间: 0.095771074295044 seconds