ReadFileString()

Share your advanced PureBasic knowledge/code with the community.
infratec
Always Here
Always Here
Posts: 7619
Joined: Sun Sep 07, 2008 12:45 pm
Location: Germany

ReadFileString()

Post 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
Rinzwind
Enthusiast
Enthusiast
Posts: 690
Joined: Wed Mar 11, 2009 4:06 pm
Location: NL

Re: ReadFileString()

Post by Rinzwind »

I think the library should be fixed. But seems Fred thinks different.

See https://www.purebasic.fr/english/viewtopic.php?p=575161
User avatar
Kwai chang caine
Always Here
Always Here
Posts: 5494
Joined: Sun Nov 05, 2006 11:42 pm
Location: Lyon - France

Re: ReadFileString()

Post by Kwai chang caine »

Works here :wink:
Thanks for sharing 8)
ImageThe happiness is a road...
Not a destination
Post Reply