[Gambas-user] Writing to a file on disk

Rolf-Werner Eilert eilert-sprachen at ...221...
Thu Nov 11 09:03:14 CET 2010


Hi Neil,

Nice to read your code. Here are some comments on it:

>
> PUBLIC SUB Button1_Click()
>
>    DIM lineIn AS String
>    DIM fileIn AS File
>    DIM fname AS String
>    fname = "/home/neilwin/basic/trial.txt"
>

Benoit introduced a new way of writing such an OPEN, you already 
received messages which proposed it. Personally, I also prefer writing 
it the old way as you do, but do not be surprised if some day it isn't 
accepted anymore ;-)

>    OPEN fname FOR READ AS #fileIn
>    LINE INPUT #fileIn, lineIn

Why do you delete the textbox and then concatenate the new string to it? 
Concatenating would only make sense if you left the existing string 
untouched, i. e. this line
>    result.Text = ""

deletes the existing string and this line

>    result.text = result.text&  lineIn

fills it with the new one anyway. You could save a line by just writing

result.text = lineIn

The following line is needless when you read from a file:
>    FLUSH #fileIn
It is only needed when you write into a stream which is buffered, just 
to make sure everything has been definitely written on disk prior to 
closing it.

>    CLOSE #fileIn
>
> END
>
> There is also a text box which I have renamed result.  I make a few changes to the line of text and then I click on another button to write the changed file back to the hard disk. Here is the code
>
> PUBLIC SUB Button3_Click()
>
>    DIM fileIn AS File
>    DIM fname AS String
>    fname = "/home/neilwin/basic/trial.txt"

Here I would say that you missed WRITE in the line
>    OPEN fname FOR CREATE AS #fileIn
it should read
OPEN fname FOR WRITE CREATE AS #fileIn

at least this is the way I do it...

>     WRITE #fileIn, result.Text

If you would like to use FLUSH, this would be the place to put it, but I 
never used it and have no bad experience with it. As far as I remember, 
CLOSE will flush the stream anyway.

>     CLOSE #fileIn
>
> END

Anyway, for simple textfile input/output, File.Read and File.Save will 
be your friends.

By the way, the other day I found that vb.net also offers both ways, but 
when you use their version of File.Save, you get a single UTF-8(?) 
character set at the beginning of the string. Actually, this made it 
useless for me. I don't know why Microsoft is doing such things, and of 
course they won't tell you in the documentation what it is supposed to 
be good for. They just recommend to use this instead of opening the 
files. Good to have Gambas ;-)

Regards

Rolf




More information about the User mailing list