Read all the contents of a file in a single instruction

New to FreeBASIC? Post your questions here.
cl4551f13d
Posts: 5
Joined: Jun 01, 2020 1:22

Read all the contents of a file in a single instruction

Postby cl4551f13d » Jun 04, 2020 6:40

Hello

I already know how to write, for example a very long string, for example, 1 Mb in a single Put.

Is there a way to get the same string in a single instruction, knowing the size to read?
dodicat
Posts: 6766
Joined: Jan 10, 2006 20:30
Location: Scotland

Re: Read all the contents of a file in a single instruction

Postby dodicat » Jun 04, 2020 6:52

Just use get instead of put.

Code: Select all

 

#include "file.bi"
Sub savefile(filename As String,p As String)
  Dim As Integer n
  n=Freefile
  If Open (filename For Binary Access Write As #n)=0 Then
    Put #n,,p
    Close
  Else
    Print "Unable to save " + filename
  End If
End Sub

Function loadfile(file as string) as String
   If FileExists(file)=0 Then Print file;" not found":Sleep:end
   var  f=freefile
    Open file For Binary Access Read As #f
    Dim As String text
    If Lof(f) > 0 Then
      text = String(Lof(f), 0)
      Get #f, , text
    End If
    Close #f
    return text
end Function

dim as string s
dim as double t

t=timer
s=string(1048576 * 10,"x")
print "data length ";len(s)/1000000;" megabytes"
savefile("file.txt",s)
print cbool(fileexists("file.txt")),"  The file has been created"
print "file size ";filelen("file.txt")/1000000;" megabytes"
dim as string L=loadfile("file.txt")
print "Retrieved length ";len(L)/1000000;" megabytes"
print "The first few characters :"
print mid(L,1,50)
print "Time taken ";timer-t
print "Press a key. . ."
sleep
kill "file.txt"
print iif(fileexists("file.txt")=0,"OK file deleted","Delete the file manually")
print "Press a key to end . . ."
sleep

 

.07 seconds here, tested gcc -O3 and gas64

Return to “Beginners”

Who is online

Users browsing this forum: No registered users and 5 guests