Other Quiz #13 - Find the bug - RandomAccessFile

Erel

B4X founder
Staff member
Licensed User
Longtime User
There is a bug in the following code. I encountered a similar bug when I wrote the BALConverter tool: http://www.b4x.com/android/forum/th...e-layouts-files-to-json-and-vice-versa.41623/

We want to write three objects to a file. However we want to be able to skip to the third object directly. So we write the position of the third object at the beginning of the file, this allows us later to read the position and jump to the third object directly.

B4X:
Sub WriteToFile (o1 As Object, o2 As Object, o3 As Object)
   Dim raf As RandomAccessFile
   raf.Initialize(...)
   raf.CurrentPosition = 4
   raf.WriteObject(o1, True, raf.CurrentPosition)
   raf.WriteObject(o2, True, raf.CurrentPosition)
   raf.WriteInt(raf.CurrentPosition, 0)
   raf.WriteObject(o3, True, raf.CurrentPosition)
   raf.Close
End Sub

Note that in most cases it is simpler and easier to use KeyValueStore class.
 

derez

Expert
Licensed User
Longtime User
When you write the position of the end of 02 in the begining of the file, you have to store this point in a variable and then write
raf.WriteObject(o3, True, [the value])
because raf.CurrentPosition now is 4 and o3 will write over o1 and o2.
 
Upvote 0

LucaMs

Expert
Licensed User
Longtime User
upload_2014-6-2_9-42-13.png


damnation. I'm here 36 hours out of 24; but I always arrive late to read the quiz. :p
 
Upvote 0
Top