writing string to stream

BlitzMax Forums/BlitzMax Programming/writing string to stream

Here's a simplified / modularized version.

Type scorelist
	Field list:scoreitem[100]
	Global listfile:TStream
	
	Method init()
		For j=0 To 99
			list[j]=New scoreitem
		Next
		open()
	End Method
	
	Method open()
'		Print "openning score file"
		listfile=OpenFile("diamonds.highscores")
		If Not listfile Then
			createhiscoresfile()
			listfile=OpenFile("diamonds.highscores")
		End If
		close()
	End Method
	Method load()
'		Print "loading score data from file stream"
		listfile=OpenFile("diamonds.highscores")
		Rem      This is not neccecary
			If Not listfile Then
				init()
				save()
			End If
		End Rem
		Local strlen:Byte
		For j=0 To 99
			If Not listfile.Eof() Then readhighscoreitem(listfile,list[j].score,list[j].name)
		Next
		close()
	End Method
	Method save()
'		Print "saving score data to file stream"
		listfile=OpenFile("diamonds.highscores")
		For j=0 To 99
			writehighscoreitem(listfile,list[j].score,list[j].name)
		Next
		close()
	End Method
	
	Method createhiscoresfile()
'		Print "no high scores file found; making new one"
		CreateFile("diamonds.highscores")
		listfile=OpenFile("diamonds.highscores")
		Local examplescores$[]=["BILLY","FRANKEY","JOEY","ANNIE","ROBBIE"]
		For j=0 To 4
			writehighscoreitem(listfile,Int((5-j)*350),examplescores[j])
		Next
		For j=5 To 99
			writehighscoreitem(listfile,list[j].score,list[j].name)
		Next
		close()
	End Method
	
	Method close()
		listfile.Close
	End Method
End Type

Function writehighscoreitem(thestream:TStream,scorey%,namey$)
	thestream.WriteInt scorey
	thestream.WriteByte Len(namey)
	thestream.WriteString namey
End Function
	
Function readhighscoreitem(thestream:TStream Var,scorey% Var,namey$ Var)
	Local strlen:Byte
	scorey=thestream.ReadInt()
	strlen=thestream.ReadByte()
	namey=thestream.ReadString(strlen)
End Function