You have a udt of fixed length strings of different sizes, or just simply strings.
You have a text file of arbitrary length, you want to load the text file into an array of these string udt's.
Because of these extra terminating chr(0), you must load via ubyte arrays, and transfer the ubtye arrays to the strings.
Code: Select all
#include "file.bi"
type arraytype
as ubyte a(1 to 50)
as ubyte b(1 to 50)
as ubyte c(1 to 10)
end type
type stringtype
as string * 50 a,b
as string * 10 c
'or
'as string a,b,c
end type
sub loadfile overload(file as string,b() as arraytype)
If FileExists(file)=0 Then Print file;" not found":Sleep:end
var f=freefile
Open file For Binary Access Read As #f
If Lof(f) > 0 Then
Get #f, , b()
End If
Close #f
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
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 load " + filename
End If
End Sub
'create a random string of characters for example
#define irange(f,l) Int(Rnd*(((l)+1)-(f))+(f))
dim as string g=string(1000,0)
for n as long=0 to len(g)-1 '65 90 97 122
g[n]=iif(rnd>.5,irange(65,90),irange(97,122))'48+rnd*9
next
'save string to text file
savefile("text.txt",g)
print "The original random file"
print loadfile("text.txt")
print
'======================== work with text file ===========
var lngth=filelen("text.txt")\sizeof(arraytype) 'get load dimension
dim as arraytype a(1 to lngth)
dim as stringtype s(1 to lngth)
'must load into ubyte arraytype
loadfile("text.txt",a())
'transfer arraytype to stringtype
for n as long=1 to ubound(a)
for m as long=1 to 50: s(n).a+= chr(a(n).a(m)):next
for m as long=1 to 50: s(n).b+= chr(a(n).b(m)):next
for m as long=1 to 10: s(n).c+= chr(a(n).c(m)):next
next
'now work with stringtype
print "string udt elements .a, .b, .c 1 to ";ubound(s)
for n as long=1 to ubound(s)
print ".a ="; s(n).a
print ".b =";s(n).b
print ".c =";s(n).c
print
next
print
'check
print "Check"
'gather up all the string udt characters
dim as string acc
for n as long=1 to ubound(s)
acc+=s(n).a+s(n).b+s(n).c
next
print
dim as long stringudtsize=len(acc)
print "part of original text file used"
dim as string L= loadfile("text.txt")
print mid(L,1,stringudtsize)
print "All the characters from the array of string udt"
print acc
print iif(acc=mid(L,1,stringudtsize),"OK","ERROR")
sleep
kill "text.txt"