Reading/Writing files

Blitz3D Forums/Blitz3D Beginners Area/Reading/Writing files

I wish to include a log file for my game - which will recird chat messages/system notes etc.

I had assumed it's not a good idea to keep the stream open ALL the time, so it will be opened, written to, then closed again each time.

This causes a problem if I need to add consecutive lines later, as each time I open it, the 'pointer' moves to the start of the file.

The immediate workaround I thought of was to read the contents each time, then re-write. Thjis of course, would take too long with large logs and defeat the object of having the file...

Is there a simple way to 'move' to the EOF?

here's my trial code:

Graphics3D 800,600,32

;CLEAR LOG FOR NEW GAME
debug=OpenFile ("Log.log")
While Not Eof (debug)
WriteLine debug,""
Wend

WriteLine debug,"START OF LOG"
CloseFile debug

;LATER ON - CONSECUTIVE LINE

sphere=CreateSphere(10)

debug=OpenFile ("Log.log")
WriteLine debug,"Created Sphere"
CloseFile debug


checkout SeekFile() for checking position in the file. and Eof() for checking the end of the file.

@Malice,
if you need to append text to a file, why don't you use the file stream commands ?

http://www.blitzbasic.com/bpdocs/command.php?name=WriteLine&ref=2d_cat

In this way, each time you open a file and write a line on it, the line will be appended at the end of the file, thus the previous file content will be preserved.

Hope this helps,
Sergio.

semar - Providin I unbderstand you correctly... that's what Ive tried!
I had assumed it's not a good idea to keep the stream open ALL the time, so it will be opened, written to, then closed again each time.



Kev, I looked at FilePos & SeekFile but neither seemed to describe how to move the position.

what you need to do is, SeekFile(stream, EOF(samestream)). That way the pointer is at the end of the file, dont try to read anything though ^_^

Great thanks!

Is there any funciton to append data to a file. For example i am drawing a line and i could like to store those x and y values in a file. If i use WriteLine function i can able to get the last x and y values. I think its overwriting the old values. So is there any file modes like "Append" mode to open a file and append the data?

Yes, you should open the file with OpenFile, and then seek to the end of the file using SeekFile:
fname$ = "test2.dat"

SeedRnd(MilliSecs())

;test if file exists
test = FileType(fname$)

;if it doesn't
If Not test Then
		
	;createfile
	file = WriteFile(fname$)

;if it does		
Else
	
	;open file
	file = OpenFile(fname$)
	;seek to end of file
	SeekFile file, FileSize(fname$)
	
End If

;add line and close file
WriteLine file, "testline " + Rand(255) 
CloseFile file

;print file
file  = ReadFile(fname$)
While Not(Eof(file))

	Print ReadLine(file)
	
Wend
CloseFile file

WaitKey()
End