how to read entire file?

New to FreeBASIC? Post your questions here.
srvaldez
Posts: 2023
Joined: Sep 25, 2005 21:54

how to read entire file?

Postby srvaldez » Feb 08, 2018 15:00

how do I read the entire file in a buffer?
suppose I have this code

Code: Select all

dim as zstring ptr buffer = allocate(10000)

how do I read the entire file into buffer ?
I tried

Code: Select all

open "testfile" for binary access read as 1 len=lof(1)
get #1,1,*buffer,10000
close 1
srvaldez
Posts: 2023
Joined: Sep 25, 2005 21:54

Re: how to read entire file?

Postby srvaldez » Feb 08, 2018 16:03

this seems to work

Code: Select all

dim as long fl
open "testfile" for binary access read as 1
fl=lof(1)
dim as ubyte buffer(fl)
get #1,,buffer()
close 1
dim as zstring ptr s=@buffer(0)
print *s
close

is there a better way or improvements ?
fxm
Posts: 9083
Joined: Apr 22, 2009 12:46
Location: Paris suburbs, FRANCE

Re: how to read entire file?

Postby fxm » Feb 08, 2018 16:31

Using a var-len string as buffer, pre-sized at the right value (the file size), you can also process the '0' characters (corresponding to the null bytes).

Not tested:

Code: Select all

dim as long fl
open "testfile" for binary access read as 1
fl=lof(1)
dim as string s=string(fl,0)
get #1,,s
close 1
print s
close
srvaldez
Posts: 2023
Joined: Sep 25, 2005 21:54

Re: how to read entire file?

Postby srvaldez » Feb 08, 2018 16:39

thank you fxm, I like your solution
sancho3
Posts: 358
Joined: Sep 30, 2017 3:22

Re: how to read entire file?

Postby sancho3 » Feb 08, 2018 17:32

This is another way:

Code: Select all

dim as integer fnum
dim as string buffer

fnum = freefile()
if open ("myfilename", for input, as #fnum) <>0 then
   ? "can't open file"
   end
endif
   buffer = input(lof(fnum), fnum)
close fnum
? buffer
srvaldez
Posts: 2023
Joined: Sep 25, 2005 21:54

Re: how to read entire file?

Postby srvaldez » Feb 09, 2018 15:55

thank you sancho3
I learned something new, was not aware that input could be used as a function.

Return to “Beginners”

Who is online

Users browsing this forum: No registered users and 12 guests