WriteChr() - problem with writing chrs to a file

Find quick help here to get you started with Hollywood
Post Reply
zylesea
Posts: 232
Joined: Tue Feb 16, 2010 12:50 am
Location: Westfalen/Germany
Contact:

WriteChr() - problem with writing chrs to a file

Post 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    

User avatar
airsoftsoftwair
Posts: 5834
Joined: Fri Feb 12, 2010 2:33 pm
Location: Germany
Contact:

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

Post 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...
zylesea
Posts: 232
Joined: Tue Feb 16, 2010 12:50 am
Location: Westfalen/Germany
Contact:

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

Post by zylesea »

Thanks Andreas, seems I had misunderstood the Seek thing. Putting out that makes the script working as intended.
Post Reply