How to read text file into array?
BlitzMax Forums/BlitzMax Beginners Area/How to read text file into array?| 
 | ||
| I'm trying to read a text file into an array without a whole lot of luck (still learning BMX).  Here is an example of what I'm trying to do: 
Type TTextFile
     Field lines:String[] 'an array of strings
     Method ReadTextFile(thisFile:String)
          Local fs:TStream
          Local fileString:String 'store the entire file as a string so we can split it later
          
		fs=ReadStream(thisFile)
		If Not fs Then RuntimeError("Could not find file: " + thisFile)
		
		While Not Eof(fs)
			fileString = fileString + ReadLine(fs)
		Wend
		lines=fileString.Split("~n") ' now make the array
		Print lines.length           ' for some reason, this always = 1, when the text file I'm loading has 100+ lines
		CloseStream(fs)
     End Method
End Type
I'm sure I'm missing something simple (This is my first experience with BMX Arrays). Anyone care to point me in the right direction? thanks | 
| 
 | ||
| Ok, i see part of the problem...  Readline discards terminating characters..  How do I preserve them?  Or should I just insert a delimiting character manually each iteration of the ReadLine loop? | 
| 
 | ||
|  Or should I just insert a delimiting character manually each iteration of the ReadLine loop?  Bingo. | 
| 
 | ||
| you don't even have to worry about any of that you can write text as lines using WriteLine such as s$ = "line one" writeLine(file,s$) s$ = "and line two" writeLine(file,s$) to read all you have to do is: local s$[2] s$[0] = readline(file) s$[1] = readline(file) edited: sorry misunderstood ignore the above but you can do it like this fileString = fileString + ReadLine(fs)+"~n" | 
| 
 | ||
| You could store the lines in a list and then convert the list into an array. Type TTextFile
	Field lines:String[] 'an array of strings
	
	Method ReadTextFile(thisFile:String)
		Local fs:TStream
		fs=ReadStream(thisFile)
		If Not fs Then RuntimeError("Could not find file: " + thisFile)
		Local stringlist:TList = New TList
		While Not Eof(fs)
			stringlist.AddLast(ReadLine(fs))
		Wend
		CloseStream(fs)
		lines = String[](stringlist.ToArray())
     End Method
End Type | 
| 
 | ||
| 
Local f:TStream = ReadFile("test.txt")
Local lines:String[] = f.ReadString(f.size()).split("~n")
KERPLOW! |