[Gambas-user] "Write" loses data

Tobias Boege taboege at gmail.com
Fri Nov 3 16:05:02 CET 2017


On Fri, 03 Nov 2017, Gianluigi wrote:
> Public Sub Main()
> 
>   Dim sPath As String = "/tmp/myFile.txt"
>   Dim i As Integer
>   Dim fl As File
> 
>   fl = Open sPath For Create
>   For i = 1 To 6
>       Write #fl, "The row " & CStr(i) & "\n"
>   Next
>   fl.Close
> 
>   fl = Open sPath For Append
>   For i = 7 To 12
>       Write #fl, "The row " & CStr(i) & "\n"
>   Next
>   fl.Close
> 
>   fl = Open sPath For Write
>   For i = 1 To 6
>       Write #fl, "The long row " & CStr(i) & "\n"
>   Next
>   fl.Close
> 
> End
> 
> 
> Rows 7, 8 and 9 are lost, but "Write" should not just overwrite the first
> six rows?
> 

You're not operating line-oriented. A file is not an array of variable-
length lines, but an array of bytes which can only grow at the end.
If you Write something at position 0, you overwrite what was previously
at position 0, you are NOT inserting data in the middle.

The rows you write last contain the additional 5 bytes " long" and you
write 6 of those long lines, resulting in 30 bytes more. The three lines
that are missing from your file had 10 bytes each, and now you see what
happens: by writing longer lines, you use up bytes allocated inside the
file and overwrite exactly 3 lines. It just so happened that the excess
data aligned well with your shorter lines, so you see no corruption and
it appears as if some data was magically lost. If you replace " long" by
" longer", you see a clearer picture:

  The longer row 1
  The longer row 2
  The longer row 3
  The longer row 4
  The longer row 5
  The longer row 6
  he row 11
  The row 12

Regards,
Tobi

-- 
"There's an old saying: Don't change anything... ever!" -- Mr. Monk


More information about the User mailing list