[Gambas-user] Writing a text file from the contents of a text area

Tobias Boege taboege at ...626...
Sun Dec 15 19:04:20 CET 2013


On Sun, 15 Dec 2013, John Rose wrote:
> Bill,
> 
> The textarea control (i.e. as you see it on the form) has a number
> of lines. But I'm also interested in an example for a textarea string 
> having a "number of lines" (i.e. it
> contains \n escape characters). Also, I'm interested in an example where 
> a string is repeatedly presented (with different values, each without a 
> \n at the end) for writing to a file.
> 
> As I previously said the file should be readable (and with each line 
> displayed on a separate line) by gedit.
> 
> My assumption is that I would have to use an Open command, followed by a 
> Write command, followed by a Close command.

OK, to structure the answers a bit:

1) Yes, you can use Open, Write, Close as you expected. It goes like this:

  Dim hFile As File
  Dim sLine As String

  ' Write to sDestionationPath. If the file already exists, we truncate it
  ' to zero length and write an entirely new one. (The other way would be to
  ' specify Append instead of Create, in which case we would... append data)
  hFile = Open sDestinationPath For Write Create

  ' Write your lines. We first split the txtArea.Text (your TextArea's
  ' contents) into lines, then write them to the file.
  '
  ' Note that Split() removes the delimiter, i.e. "\n", but Print agains
  ' adds it to the output. So the result is unchanged.
  For Each sLine In Split(txtArea.Text, "\n")
    Print #hFile, sLine
  Next

  ' Close the file.
  Close #hFile

Note that this isn't the most elegant or even most efficient solution - by
far. It only serves as an example of how it looks like. You don't need, for
example, to split the TextArea contents first and then merge them again as
you write the file. You can also directly write the contents:

  hFile = Open ...
  Write #hFile, txtArea.Text, Len(txtArea.Text)
  Close #hFile

Now let us consider CSV files or the like where you always have integral
lines to write. In this case, you can substitute Write by Output in the Open
statement:

  hFile = Open sDestinationPath For Output Create

The only difference is that For Output designs the stream to be buffered. It
is more efficient then. You can also use File.Begin() and File.Send() to
explicitly buffer if you feel needed.

As you noticed, there are still other ways to write your file but these
really depend on what you want to do.

2) As the others pointed out, you normally don't need to call upon Open to
write data to a file which you already have assembled in a String. You use
the File.Save() method instead:

  File.Save(sDestinationPath, txtArea.Text)

Regards,
Tobi

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




More information about the User mailing list