- This code provides a simple wrapper for some of the C “stdio” functions
defined in
<cstdio>
. The blob wraps the
file pointer returned from fopen() and also keeps a few other
values for debugging (the mode, flags, filename from the call to fopen())
plus a buffer for read operations.
- A utility class‘PlOptionsFlag` is defined in fileSWI-cpp2-flags.h,
for mapping a list of atoms to a bit-field flag. For example, the list
[search,read]
would map to‘examPL_FILE_SEARCH|PL_FILE_READ‘.
- The
MyFileBlob
struct defines the blob that wraps a
FILE*
. The constructor (which is called by predicate
my_file_open/4)
converts the flags term (a list of atoms or strings) to a
flag that is passed to PL_get_file_name(), to convert the filename
to a string containing the abslute file name. This is then passed to fopen(),
together with the
mode. If the call to fopen() fails, a C++ exception is
thrown, to be handled by Prolog. Other errors, such as a wrong argument
type to PL_get_file_name() can also cause an exception.
- MyFileBlob::read() ensures that the buffer is big enough and
then calls‘fread()‘to return the buffer's contents.
- MyFileBlob::eof() and MyFileBlob::error() call feof()
and ferror() respectively. They can be used to check the status
of the call to MyFileBlob::read().
- The destructor calls MyFileBlob::close() and outputs a
warning if it fails - a destructor is not allowed to throw a C++
exception, so this is the best we can do; it's better if the programmer
explicitly closes the file rather than depending on the garbage
collector to free the blob.
- MyFileBlob::close() calls fclose(). It then sets the
FILE*
to null, so that close won't be done twice.
- MyFileBlob::compare_fields(), MyFileBlob::write_fields(),
MyFileBlob::write_fields_only(), MyFileBlob::portray() are
similar to the same methods in
MyBlob
in section
1.6.8.5.
- Predicate my_file_open(File,Filename,Mode,Flags) calls the
MyFileBlob
constructor with Filename, Mode,
flags and unifies the blob with File.
- Predicate my_file_close/1
calls MyFileBlob::close(), checks for an error and creates a
Prolog error if the close failed.