[Gambas-user] "Write" loses data

T Lee Davidson t.lee.davidson at gmail.com
Fri Nov 3 15:56:07 CET 2017


On 11/03/2017 10:15 AM, 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?
> 
> Regards
> Gianluigi
> 

No, it shouldn't. A text file is not a file of rows (or lines) but a file of characters (bytes).

 From http://gambaswiki.org/wiki/lang/open, "Unlike other Basic dialects, Gambas will never delete the contents of a file when 
it is opened by the WRITE keyword. So, if the new content is smaller than the old one, some garbage of the old file version will 
remain at the end of the new file. To avoid this, open the file including the CREATE keyword."

After opening and writing to the file in Write mode, lines 10 - 12 are now garbage. This just isn't readily apparent because 
after the Create and Append mode writings, lines 1 - 9 consist of 90 bytes in the file. And then after the Write mode writing, 
the "long" rows 1 - 6 also consist of exactly 90 bytes. (The short rows are 10 bytes long [9 x 10 = 90]. The long rows are 15 
bytes long [6 x 15 = 90].)


-- 
Lee


More information about the User mailing list