Page 1 of 1

WriteChr() - problem with writing chrs to a file

Posted: Fri Jul 12, 2013 1:13 am
by zylesea
I have a little prob with writing chrs to a file. Probably I don't see the forrest for the trees, but I am really stuck here. I think the following snipped down mini program should write ABCD... to a file, but it doesn't it writes CEG... instead while the counter "my_frame" gets increased by 1 only everytime the routine is called.

Code: Select all

cfilename$= "Ram:blabla"
OpenFile (1,cfilename$, #MODE_WRITE)
toggle_rec=true
my_frame=0  

Function p_rec_data()
    If toggle_rec=True
    my_frame=my_frame+1
    DebugPrint (my_frame)
    t=GetFileAttributes (cfilename$)
    seek_pos=t.size
    Seek (1, seek_pos)
    WriteChr(1, 65+my_frame)
    EndIf
EndFunction

Function p_main()
    p_rec_data()
EndFunction

SetInterval(0, p_main, 125); 8Hz

Repeat
    WaitEvent
Forever    


Re: WriteChr() - problem with writing chrs to a file

Posted: Sat Jul 13, 2013 12:11 pm
by airsoftsoftwair
There are several problems with this script:

1. You're querying the file size while writing to the file. This is asking for trouble because I/O routines are normally buffered due to efficiency reasons, i.e. data won't be written to the file until it has reached a certain size because it would be very very inefficient to turn on the drive motor for writing just a single byte :) Bottom line: Querying file size while writing to it is highly unreliable and won't get you the current size. There's a function named FilePos() which returns the current cursor position which you can use instead.

2. Why do you call Seek() here at all? It is not necessary because WriteChr() will automatically advance the file cursor by 1. So you don't have to seek manually to the end.

3. The function will never write "A" (= ASCII 65) because my_frame is increased by one right at the function entry point, thus you will always start at ASCII 66 which is equivalent to the letter "B" but because querying the file size while writing is unreliable it can also happen that it starts somewhere else... depends on how long 0 is returned as the file size...

Re: WriteChr() - problem with writing chrs to a file

Posted: Mon Jul 15, 2013 12:07 am
by zylesea
Thanks Andreas, seems I had misunderstood the Seek thing. Putting out that makes the script working as intended.