Thus far, we have only considered the default behaviour of a Channel in reading and writing Objects through a program's standard input and output streams. We will now consider how to access Objects stored in files more directly.
Because the AST library is designed to be used from more than one
language, it has to be a little careful about reading and writing to
files. This is due to the incompatibilities that often exist between
the file I/O facilities provided by different languages. Fortunately,
this ties in well with the principle that AST should also be
independent of any particular data storage system, which we mention
again in .
What this means in practice is that you must provide some simple C
functions that perform the actual transfer of data to and from files
and similar external data stores. The functions you provide are
supplied as the source and/or sink function arguments to astChannel
when you create a Channel (). An example is
the best way to illustrate this.
Consider the following simple function called Source. It reads a single line of text from a C input stream and returns a pointer to it, or NULL if there is no more input:
#include <stdio.h> #define LEN 200 static FILE *input_stream; const char *Source( void ) { static char buffer[ LEN + 2 ]; return fgets( buffer, LEN + 2, input_stream ); }
Note that the input stream is a static variable which we will also access from our main program. This might look something like this (omitting error checking for brevity):
/* Open the input file. */ input_stream = fopen( "infile.ast", "r" ); /* Create a Channel and read an Object from it. */ channel = astChannel( Source, NULL, "" ); object = astRead( channel ); ... /* Annul the Channel and close the file when done. */ channel = astAnnul( channel ); (void) fclose( input_stream );
Here, we first open the required input file, saving the resulting FILE pointer. We then pass a pointer to our Source function as the first argument to astChannel when creating a new Channel. When we read an Object from this Channel with astRead, the Source function will be called to obtain the textual data from the file, the end-of-file being detected when this function returns NULL.
AST A Library for Handling World Coordinate Systems in Astronomy