Appending to a file.

Previous topic - Next topic

Hatonastick

I'm trying to add a line of text to the end of a file (for a simple log system) by opening the file, jumping to the end and then using WRITELINE to add the log entry; however currently it just overwrites any existing data.  Something like this (which obviously doesn't work or I'm using the commands in the wrong way):
Code (glbasic) Select
FUNCTION SysLog: msg$
LOCAL time$[]
LOCAL filename$

// Grab current time and date.
GetTime(time$[])

// Create the current file name.
filename$ = "./World/Logs/SysLog-"+time$[0]+time$[1]+time$[2]+".txt"

// Write the given message to the top of the file.
IF OPENFILE(1, filename$, FALSE)
// Jump to the end of the file.
FILESEEK 1, 0, -1
// Write time plus message.  Date is already indicated by file name.
WRITELINE 1, time$[3]+":"+time$[4]+":"+time$[5]+" "+msg$
CLOSEFILE 1
// Something went wrong, we should inform the administrator by writing to
// the console.
ELSE
ConLog("SYS: Failed to open/create SysLog() file.")
ENDIF
ENDFUNCTION

Does this mean that the only way I can do this is to read the current file contents into an array or similar, append my extra text to the end of the array and then write the whole array back to the file?

It does occur to me that it's been a while since I did any reading/writing of files and I think I might be a little confused as to what I can and can't do.

MrTAToad

Looking at the help file, it does look as though there is no appending system - just reading in or writing a new (or over a current) file.

Kitty Hello

Yes. Bad, isn't it?
I'll think about it.
Maybe APPENDFILE instead of OPENFILE?

MrTAToad

Why not an extra value to OPENFILE ?  Might be quicker that way... :)

Hatonastick

#4
Ahh ok, so read file in, append in memory, then write it back out it is then. :)

There a way to get the size of a file?  Or again, do you have to read it in and count the bytes yourself?

Kitty Hello

GETFILESIZE might help.

Hatonastick

What are you doing giving GLB functions names that are actually meaningful?  :whistle:  Ok time for me to stop coding and go to bed.  Don't know how I missed that one...