Opening The User-Defined Stream

Depending on the specific user-defined stream, there are different operations needed for the stream. A stream that operates on a file needs to open the file; a stream that operates for inter-process communication needs to build the connection to different process. Our example stream operates on files, so we just open the file to get file descriptor. The parameters of our function and local variables in the function are also listed.

     QP_stream *
     open_bin(filename, modename, error_num)
         char   *filename, *modename;
         int    *error_num;
             BinStream       *stream;
             QP_stream       *option;
             int             fd, mode;
             switch (*modename) {
             case 'r': mode = QP_READ;
                       fd = open(filename, O_RDONLY, 0000);
             case 'w': mode = QP_APPEND;
                       fd = open(filename, O_WRONLY|O_CREAT|O_TRUNC,
             case 'a': mode = QP_APPEND;
                       fd = open(filename, O_WRONLY|O_CREAT, 0666);
             default:  *error_num = QP_E_BAD_MODE;
                       return QP_NULL_STREAM;
             if (fd < 0) {
                 *error_num = errno;
                 return QP_NULL_STREAM;
             ......  allocate space and set user-stream fields  ......
             ......  set up QP_stream structure fields  ......
             ......  register the created QP_stream  ......
             return &stream->qpinfo;

This function can be called from Prolog using the Prolog calling C interface described in fli-p2f. The address returned by this function is converted into the Prolog representation of a stream using stream_code/2.