Basic file reading?

BlitzMax Forums/BlitzMax Beginners Area/Basic file reading?

The forum is locked. These are the original blitzbasic.com forums, kept so they can still be read. No new topics, replies or edits can be made here. To join in, head over to the Blitz3D+ forums.

I accidently posted here and felt kind of bad for not giving a decent answer.

so i knocked this up. I hope it helps:

Local filename$ = "CSVTEST.csv"
out=WriteStream(filename$)

If Not out RuntimeError "Failed to open a WriteStream to file mygame.ini"

WriteLine out,"comma, seperated , values"
WriteLine out,"This,is,a,long,Line"
WriteLine out,""
WriteLine out,"Let's see if it handles 6 consecutive commas ,,,,,,"


CloseStream out

Print "File "+filename$+" created, bytes="+FileSize(filename$)


in = OpenStream(filename$)

While Not Eof( in)
	line_from_file$ = ReadLine(in)
	
	Local mycsv$[] = readcsv(Line_from_file$)

	For words:String = EachIn mycsv

		Print words
	Next

	
Wend

Function readCSV:String[]( csvline:String , delimeter:Int= 44 )
	Local stringarray:String[1]
	Local word:String	
	Local letter:Int
	Local L = Len(csvline)
	If L=0 Then Return Null
	
		
	For Local d:Int = 0 To L-1
		
		If csvline[d] = delimeter	' default = comma ' , ' 
			stringarray = stringarray[..Len(stringarray)+1]	' resize the array to add another character
			word$ = Null
			letter = 0
		Else
				word$ = word+Chr(csvline[d])
				stringarray[Len(stringarray)-1] = word
				letter:+1
		EndIf
		
	Next
	Return stringarray
End Function



this should handle reasonably complex files. keep in mind that 'proper' csv parsers probably can identify fields that have commas in them (usually by wrapping them in quotes:

john smith , "13444 lollypop lane,sarasota, fla" , meateater

the above would be 5 elements in my code but should be 3 elements. should not be too hard if that kind of complexity is what you are after. but to be honest, if you get to the point where you need *proper* CSV reading, you should maybe move on to XML. Brucey and John J both made excellent XML modules for Blitzmax