how to read entire file?

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

how to read entire file?

Post by srvaldez »

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: 3379
Joined: Sep 25, 2005 21:54

Re: how to read entire file?

Post by srvaldez »

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
Moderator
Posts: 12107
Joined: Apr 22, 2009 12:46
Location: Paris suburbs, FRANCE

Re: how to read entire file?

Post by fxm »

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: 3379
Joined: Sep 25, 2005 21:54

Re: how to read entire file?

Post by srvaldez »

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

Re: how to read entire file?

Post by sancho3 »

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: 3379
Joined: Sep 25, 2005 21:54

Re: how to read entire file?

Post by srvaldez »

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