writing string to stream

BlitzMax Forums/BlitzMax Programming/writing string to stream

Hello, all. According to my dad, (also a programmer,) what I am about to show you is NOT completely origonal, but I still made it up without knowing about it, so I'm kinda proud :D.

I'm posting an example that can manage a high scores list with a hundred entries (haven't written the sorter, but the relevant stream management is there).

Here's the idea:

When writing a string to a stream, there are three different methods.

The first two methods are: write strings that are always the same number of bytes, or using "tehStream.WriteLine(str$)" to just write a single line of text with a line terminator byte at the end.

My method is to write a value (a byte is best) before the string that says how long it will be, then read it based on the length stated.

There! Ooh, I think my ego just went from shriveled prune to monkey carcass (slightly better than the prune one)! Oops, lost it again. Damn!

Edit: Okay it's up in the code archive. It's called "High Score Type"

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