Page 1 of 1

ReadFileString()

Posted: Sat Mar 26, 2022 4:01 pm
by infratec
Since ReadString() with #PB_File_IgnoreEOL flag is very slow on larger files,
I think the solution from:

https://www.purebasic.fr/english/viewtopic.php?t=78892

should be presented in Tricks 'n' Tips:

Code: Select all

CompilerIf #PB_Compiler_IsMainFile
  EnableExplicit
CompilerEndIf


Procedure.s ReadFileString(Filename$)
  
  Protected.i File, BytesToRead, BOM
  Protected Content$, *Buffer
  
  
  File = ReadFile(#PB_Any, Filename$, #PB_File_SharedRead)
  If File
    BOM = ReadStringFormat(File)
    BytesToRead = Lof(File) - Loc(File)
    
    *Buffer = AllocateMemory(BytesToRead)
    If *Buffer
      If ReadData(File, *Buffer, BytesToRead) = BytesToRead
        Select BOM
          Case #PB_Unicode
            Content$ = PeekS(*Buffer, BytesToRead / 2, #PB_Unicode)
          Case #PB_UTF8
            Content$ = PeekS(*Buffer, BytesToRead, #PB_UTF8|#PB_ByteLength)
          Case #PB_Ascii
            Content$ = PeekS(*Buffer, BytesToRead, #PB_Ascii)
        EndSelect
      EndIf
      FreeMemory(*Buffer)
    EndIf
    
    CloseFile(File)
  EndIf
  
  ProcedureReturn Content$
  
EndProcedure


CompilerIf #PB_Compiler_IsMainFile
  Define Filename$
  
  Filename$ = OpenFileRequester("Choose a text file", "", "TXT|*.txt", 0)
  If Filename$
    Debug ReadFileString(Filename$)
  EndIf
CompilerEndIf

Re: ReadFileString()

Posted: Fri Apr 08, 2022 10:57 am
by Rinzwind
I think the library should be fixed. But seems Fred thinks different.

See https://www.purebasic.fr/english/viewtopic.php?p=575161

Re: ReadFileString()

Posted: Fri Apr 08, 2022 5:43 pm
by Kwai chang caine
Works here :wink:
Thanks for sharing 8)