#1 2017-11-14 05:34:35

squirrel
Member
Registered: 2015-08-13
Posts: 146

Suggestion for expanding StringFromFile

@ab

Would it be possible to expand the StringFromFile function to allow getting parts of a file?  This would be very handy when serving big files via http with RangeRequests.  Maybe something similar with defaults which would allow the current usage to continue working unaffected:

  function StringFromFile(const FileName: TFileName; const StartPos: Int64 = 0; const Count: Int64 = 0): RawByteString;
  var F: THandle;
      Size, BytesToCopy, BytesCopied: integer;
  begin
    result := '';
    if (FileName='') or (StartPos < 0) or (Count < 0) then
      exit;
    F := FileOpenSequentialRead(FileName);
    if PtrInt(F)>=0 then
    begin
      Size := GetFileSize(F,nil);
      if Size>0 then
      begin
        BytesToCopy := Size - StartPos;
        if (Count > 0) and (BytesToCopy >= Count) then //count = 0 should always return the entire file/rest of the file
          BytesToCopy := Count;

        SetLength(result, BytesToCopy);
        if StartPos > 0 then
          FileSeek(F, StartPos, 0);
        BytesCopied := FileRead(F,pointer(result)^,BytesToCopy);
        if BytesCopied < 0 then //FileRead failed
          result := ''
        else
        if BytesCopied < BytesToCopy then //less bytes were left to read than anticipated
          SetLength(result, BytesCopied);
      end;
      FileClose(F);
    end;
  end;

Last edited by squirrel (2017-11-14 05:36:51)

Offline

Board footer

Powered by FluxBB