Faster file read & write data routines (INPUT/OUTPUT)
Posted: Sun Apr 10, 2016 3:21 am
These routines kind of mimic Qbasics file INPUT £ OUTPUT functions. They read and write many bytes at a time. It uses the file readdim and writedim to read and write data instead of the slower read & write on byte at a time method.
The demo code makes a 5000 byte file and reads & writes data to it using both methods to show the speed difference. Helpful when loading and saving large file data.
- Dav
The demo code makes a 5000 byte file and reads & writes data to it using both methods to show the speed difference. Helpful when loading and saving large file data.
- Dav
Code: Select all
'InputOutput.txt
'Faster File data read & write routines.
'Works like Qbasic file input/output ones.
'Reads and writes chunks of data at a time.
'Faster than the one byte read/write method.
'Reads/writes using readdim/writedim instead.
'Code by Dav, April/2016
option base 1
'make a test file to use first
f$="testfile.dat"
print "INPUT & OUTPUT functions test."
print "Making testfile.dat of 5000 bytes to use..."
print
for t = 1 to 5000
file f$ write 33
next t
'read file using file read byte method
print "Reading 'file read' one byte method..."
t1=time()
a$=""
file f$ setpos 0
for t = 1 to 5000
file f$ read c
a$=a$&chr$(c) 'build data...
next t
print "Read 5000 bytes in ";
print time()-t1;" secs"
print
'read file using new file input method
print "Reading new INPUT$ method..."
t1=time()
a$=input$(f$,1,-1) 'load whole file (-1)
print "Read 5000 bytes in ";
print time()-t1; " secs"
print
print "Writing 'file write' one byte method..."
t1=time()
file f$ setpos 0
for t = 1 to 5000
file f$ write asc(mid$(a$,t,1))
next t
print "Wrote 5000 bytes in ";
print time()-t1;" secs"
print
print "Writing new OUTPUT method..."
t1=time()
output(f$,1,a$)
print "Wrote 5000 bytes in ";
print time()-t1; " secs"
print
end
'=====================================
def input$(f$,pos,bytes)
'Reads data from file - returns it as input$
'
'f$ = file to read
'pos = position in file to start reading
'bytes = how many bytes to read
'
'note: if bytes=-1 then reads entire file.
'make sure values are in bounds
if pos < 1 then pos=1
if bytes>file_size(f$) or bytes=-1 then
bytes=file_size(f$)
end if
'read entire file into m array
file f$ setpos 0
file f$ readdim m
'read location, build data
t$=""
for r=pos to (pos+bytes-1)
t$=t$&chr$(m(r))
next r
'return file data as input$
input$=t$
end def
'==================================
def output(f$,pos,out$)
'writes data out to given file.
'
'f$ = file to write to
'pos = position in file to start saving to
'out$ = the data to write to file
'load file into m array
file f$ setpos 0
file f$ readdim m
'change m array data
s=1
for r=pos to (pos+(len(out$))-1)
m(r)= asc(mid$(out$,s,1))
s=s+1
next r
'save file with m changes
file f$ setpos 0
file f$ writedim m
end def
'===================================