Jump to content

Append a record to the end of a text file: Difference between revisions

→‎{{header|Wren}}: Discovered an undocumented method to append a record to an existing file.
(→‎{{header|Wren}}: Discovered an undocumented method to append a record to an existing file.)
Line 3,819:
Although Wren has basic classes to work with the file system, these are only available when creating standalone scripts using the command line interpreter (CLI) and not when Wren is being embedded. In the latter case it relies on the host application for such support.
 
To append a record to an existing file in a CLI script, a little digging is required as the method to do this (''File.openWithFlags'') is currently undocumented. However, the following works fine.
Currently, in scripts written for the CLI, there appears to be no easy way to append something to an existing file.
<lang ecmascript>import "io" for File, FileFlags
 
The work-around is to read the contents of the file (if large it can be read in chunks) and write them to a new file together with whatever needs to be appended. One then needs to delete the existing file and rename the new one.
 
However, to avoid the latter steps, a file can be created using an existing name - it simply truncates the existing contents before anything is written - so care obviously needs to be taken when using this facility.
<lang ecmascript>import "io" for File
 
var records = [
Line 3,845 ⟶ 3,841:
 
// Append the new record to the file and close it.
File.createopenWithFlags(fileName, FileFlags.writeOnly) { |file|
file.writeBytes(contents)
file.writeBytes(newRec + "\n")
}
Line 3,883 ⟶ 3,878:
|}
<br>
 
=={{header|Yabasic}}==
<lang Yabasic>a = open("passwd", "a") // Open the file for appending, i.e. what you write to the file will be appended after its initial contents.
9,485

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.