RosettaCodeData/Task/Read-a-configuration-file/FreeBASIC/read-a-configuration-file.b...

97 lines
2.7 KiB
Plaintext

' FB 1.05.0 Win64
Sub split (s As Const String, sepList As Const String, result() As String)
If s = "" OrElse sepList = "" Then
Redim result(0)
result(0) = s
Return
End If
Dim As Integer i, j, count = 0, empty = 0, length
Dim As Integer position(Len(s) + 1)
position(0) = 0
For i = 0 To len(s) - 1
For j = 0 to Len(sepList) - 1
If s[i] = sepList[j] Then
count += 1
position(count) = i + 1
End If
Next j
Next i
Redim result(count)
If count = 0 Then
result(0) = s
Return
End If
position(count + 1) = len(s) + 1
For i = 1 To count + 1
length = position(i) - position(i - 1) - 1
result(i - 1) = Mid(s, position(i - 1) + 1, length)
Next
End Sub
Type ConfigData
fullName As String
favouriteFruit As String
needsPeeling As Boolean
seedsRemoved As Boolean
otherFamily(Any) As String
End Type
Sub readConfigData(fileName As String, cData As ConfigData)
Dim fileNum As Integer = FreeFile
Open fileName For Input As #fileNum
If err > 0 Then
Print "File could not be opened"
Sleep
End
End If
Dim ln As String
While Not Eof(fileNum)
Line Input #fileNum, ln
If ln = "" OrElse Left(ln, 1) = "#" OrElse Left(ln, 1) = ";" Then Continue While
If UCase(Left(ln, 8)) = "FULLNAME" Then
cData.fullName = Trim(Mid(ln, 9), Any " =")
ElseIf UCase(Left(ln, 14)) = "FAVOURITEFRUIT" Then
cData.favouriteFruit = Trim(Mid(ln, 15), Any " =")
ElseIf UCase(Left(ln, 12)) = "NEEDSPEELING" Then
Dim s As String = Trim(Mid(ln, 13), Any " =")
If s = "" OrElse UCase(s) = "TRUE" Then
cData.needsPeeling = True
Else
cData.needsPeeling = False
End If
ElseIf UCase(Left(ln, 12)) = "SEEDSREMOVED" Then
Dim s As String = Trim(Mid(ln, 13), Any " =")
If s = "" OrElse UCase(s) = "TRUE" Then
cData.seedsRemoved = True
Else
cData.seedsRemoved = False
End If
ElseIf UCase(Left(ln, 11)) = "OTHERFAMILY" Then
split Mid(ln, 12), ",", cData.otherFamily()
For i As Integer = LBound(cData.otherFamily) To UBound(cData.otherFamily)
cData.otherFamily(i) = Trim(cData.otherFamily(i), Any " =")
Next
End If
Wend
Close #fileNum
End Sub
Dim fileName As String = "config.txt"
Dim cData As ConfigData
readConfigData fileName, cData
Print "Full name = "; cData.fullName
Print "Favourite fruit = "; cData.favouriteFruit
Print "Needs peeling = "; cData.needsPeeling
Print "Seeds removed = "; cData.seedsRemoved
For i As Integer = LBound(cData.otherFamily) To UBound(cData.otherFamily)
Print "Other family("; Str(i); ") = "; cData.otherFamily(i)
Next
Print
Print "Press any key to quit"
Sleep