程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> Delphi >> delphi 如何快速讀取文本文件

delphi 如何快速讀取文本文件

編輯:Delphi
You may try this: function R(const FileName: string): string;
var
  M: TFileStream;
begin
  M := TFileStream.Create(FileName, fmOpenRead);
  try
    SetLength(Result, M.Size);
    M.Read(Result[1], M.Size);
  finally
    M.Free;
  end;
end;

Solve 2: As an alternative to Christian's suggestion, you can also use a memory-mapped file: function 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}
            CloseHandle(hFile);
      {Close file handle - as long is vIEw is open it will persist}
            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;
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved