Non-sequential Read/Writes

BlitzMax Forums/BlitzMax Beginners Area/Non-sequential Read/Writes

Tachyon(Posted 2005) [#1]
Can anyone supply me with (or point me to) some sample code for doing non-sequential reads & writes to a file. I think this is done via ReadStream/WriteStream, but I'm not sure.

Thanks!!


Perturbatio(Posted 2005) [#2]
ReadString, WriteString etc all use the streams current position to determine where to read or write.

Use SeekStream and StreamPos to set or determine position and then read or write as you see fit.

Strict

CreateFile("c:\testout.txt") 'openstream requires a file exists before you can use it.

Local myStream:TStream = OpenStream("c:\testout.txt")

If Not myStream Then RuntimeError("Error creating c:\testout.txt")

WriteString(myStream, "This is a test")
Print StreamPos(myStream)

SeekStream(myStream, 0)
Print ReadString(myStream, StreamSize(myStream))

SeekStream(myStream, 10)
WriteString(myStream, "Mongoose")
Print StreamPos(myStream)
SeekStream(myStream, 0)
Print ReadString(myStream, StreamSize(myStream))

CloseStream(myStream)



Tachyon(Posted 2005) [#3]
Thanks Perturbatio!

Question: You did SeekStream by pointing to the 10th Character place in the file. Can this be done by checking for breaks like commas, tabs, or carriage returns? My final program will need to open a text file which will resemble something like a spreadsheet, and jump down to a specific ROW in order to read several fields. For example, how could I open a file and jump down to Row 3, and read the three fields...or change one of the fields in row 3, from "Red" to "White" for example.

1, Honda, Civic, Blue
2, Ford, Mustang, Black
3, Porsche, 911, Red
4, Pontiac, GrandPrix, Blue


Perturbatio(Posted 2005) [#4]
if you are using fixed field sizes then you can easily tell where the 3rd row is.
If you are not, you need to establish a delimeter character, (in this case you are using comma which is ok if you are not allowing users to enter data) and read each byte until you encounter it.
Your next problem is reading in the string value (you need to know how long the string is), you can obviously do this by finding the distance from the first delimeter (or the beginning of the file) to then next and reset the stream postion to the start point, then read in the string.

*EDIT*
if each row is on a seperate line in the text file you can use the linefeed at the end of the line as a row delimiter, so in blitz you would look for "~n".


Tachyon(Posted 2005) [#5]
Thanks for all your help Perturbatio!

I think I can take it here. I guess if my file read/writes needs get much more demanding I should just think about communicating with an actual database (SQL or Access). I just want to avoid that extra layer of programming if I have to.


Perturbatio(Posted 2005) [#6]
just remember that if you are reading a large amount of data from a file, use flushmem inside your reading loop, this will dramatically speed up operations and cut down on memory usage.