Recent

Author Topic: Can't read from TFileStream  (Read 1804 times)

LemonParty

  • Full Member
  • ***
  • Posts: 165
Can't read from TFileStream
« on: December 27, 2024, 05:05:39 pm »
I am using next function to read from file
Code: Pascal  [Select][+][-]
  1. function ReadStringFromFile(FileName: string): RawByteString;
  2. var
  3.   S: TFileStream;
  4.   Count: SizeInt;
  5. begin
  6.   S := TFileStream.Create(FileName, fmOpenRead or fmShareDenyNoneFlags);
  7.   try
  8.     Count := S.Size;
  9.     SetLength(Result, Count);
  10.     S.ReadBuffer(Pointer(Result)^, Count);
  11.   finally
  12.     S.Free;
  13.   end;
  14. end;
When I reach line S.ReadBuffer(Pointer(Result)^, Count); an exeption (EReadError: Stream read error) occurs. What it could be?
Lazarus v. 4.99. FPC v. 3.3.1. Windows 11

cdbc

  • Hero Member
  • *****
  • Posts: 2104
    • http://www.cdbc.dk
Re: Can't read from TFileStream
« Reply #1 on: December 27, 2024, 05:34:38 pm »
Hi
Easy Peasy... your "fmShareDenyNoneFlags" doesn't exist!
Try this instead:
Code: Pascal  [Select][+][-]
  1. program streamtostring;
  2. {$mode objfpc}{$H+}
  3. uses classes,sysutils;
  4.  
  5. var
  6.   ls: string;
  7.   fn: string;
  8.  
  9. function ReadStringFromFile(FileName: string): RawByteString;
  10. var
  11.   S: TFileStream;
  12.   Count: SizeInt;
  13. begin
  14.   { below are the correct file-mode-flags }
  15.   S := TFileStream.Create(FileName, fmOpenRead or fmShareDenyNone);
  16.   try
  17.     Count := S.Size;
  18.     SetLength(Result, Count);
  19.     S.ReadBuffer(Pointer(Result)^, Count);
  20.   finally
  21.     S.Free;
  22.   end;
  23. end;
  24.  
  25. begin
  26.   if paramcount >= 1 then begin
  27.     fn:= paramstr(1);
  28.     if FileExists(fn) then begin
  29.       writeln('Contents of ',fn,':');
  30.       ls:= ReadStringFromFile(fn);
  31.       writeln('(i) Number of bytes: ',length(ls));
  32.       writeln(ls);
  33.     end;
  34.   end else writeln('Usage: streamtostring sometxtfile');
  35. end.
  36.  
HTH
Regards Benny
If it ain't broke, don't fix it ;)
PCLinuxOS(rolling release) 64bit -> KDE5 -> FPC 3.2.2 -> Lazarus 3.6 up until Jan 2024 from then on it's both above &: KDE5/QT5 -> FPC 3.3.1 -> Lazarus 4.99

LemonParty

  • Full Member
  • ***
  • Posts: 165
Re: Can't read from TFileStream
« Reply #2 on: December 27, 2024, 05:45:51 pm »
Yes. It works. Thank you.
Lazarus v. 4.99. FPC v. 3.3.1. Windows 11

 

TinyPortal © 2005-2018