##
Writing Objects to Files

As for reading, writing Objects to files can be done in two different ways. Again, the simple approach is to use the SinkFileSinkFile attribute of the ChannelChannel. For instance, the following will write a pair of Objects to a text file called “fred.txt”:

249#249

Note, the act of clearing the attribute tells AST that no more output will be written to the file and so the file is then closed. If the attribute is not cleared, the file will remain open and further Objects can be written to it. The file will always be closed when the Channel is deleted.

If the details of the language's I/O system on the computer you are using means that the above approach cannot be used, then we can write a Sink function, that writes a line of output text to a file, and use it in basically the same way as the Source function in the previous section (§15.13):

250#250

Note that we must supply the final newline character ourselves.

In this case, our main program would supply a pointer to this Sink function as the second argument to astChannelastChannel, as follows:

251#251

Note that we can specify a source and/or a sink function for the Channel, and that these may use either the same file, or different files according to whether we are reading or writing. AST has no knowledge of the underlying file system, nor of file positioning. It just reads and writes sequentially. If you wish, for example, to reposition a file at the beginning in between reads and writes, then this can be done directly (and completely independently of AST) using standard C functions.

If an error occurs in your source or sink function, you can communicate this to the AST library by setting its error status to any error value using astSetStatusastSetStatus (§4.15). This will immediately terminate the read or write operation.

Note, if a value is set for the SinkFile attribute, the astWriteastWrite function will ignore any sink function specified when the Channel was created.