Sample file-access UDR

The following sample UDR, logmsg(), uses the DataBlade® API file-access functions to output messages to an external file:
#include <mi.h>
#include <fcntl.h>
#include <errno.h>

void logmsg (filename, message, Gen_fparam)
   mi_lvarchar *filename,
   mi_lvarchar *message,
   MI_FPARAM *Gen_fparam
{
   mi_integer fd, /* file descriptor */
            ret, /* return status from file-access funcs 
                  *functions
                  */
            error; /* mi_file_errno() errno return */

   mi_string pathname[256], /* mi_lvarchar_to_buffer() result */
            *msg_str, /* mi_lvarchar_to_string() result */
            *newline = "\n", /* output new line */
             msg_error[150], /* errno error message */
             tmp_error[150], /* temp error message */
            *p;

   if ( mi_get_varlen(filename) >= sizeof(pathname) )
      {
      mi_db_error_raise(NULL, MI_EXCEPTION,
         "Pathname exceeded 255 characters!");
      return;
      }

   mi_var_to_buffer(filename, pathname);
   msg_str = mi_lvarchar_to_string(message);

   fd = mi_file_open(pathname, 
      O_WRONLY | O_APPEND | O_CREAT, 0644);
   if ( fd == MI_ERROR )
      {
      error = mi_file_errno();
      switch( error )
         {
         /* Include your favorite errors from
          * /usr/include/sys/errno.h.
          */
         case ENOENT:
            p = "No such file or directory";
            break;
         case EACCES:
            p = "Permission denied";
            break;
         case EISDIR:
            p = "Pathname is a directory instead of file";
            break;
         default:
            p = "Unhandled errno case";
            break;
         }

      tmp_error = "logmsg: mi_file_open() failed for";
      sprintf(msg_error, "%s '%s' -- %s (errno=%d)",
         tmp_error, pathname, p, error);

      mi_db_error_raise(NULL, MI_EXCEPTION, msg_error);
      return; /* not reached */
      }

   ret = mi_file_write(fd, msg_str, strlen(msg_str));
   if( ret == MI_ERROR )
      {
         error=mi_file_errno();
         switch( error )
            {
            case ENOSPC:
               p = "No space left on device";
               break;
            default:
               p = "Unhandled errno case";
               break;
            }

         tmp_err = "logmsg: mi_file_write() failed for"
         sprintf(msg_error, "%s '%s' -- %s (errno=%d)",
            tmp_err, pathname, p, error);
         mi_db_error_raise(NULL, MI_EXCEPTION, msg_error);
         return; /* not reached */
         }

   ret = mi_file_write(fd, newline, strlen(newline));
   if( ret == MI_ERROR )
      {
      mi_db_error_raise(NULL, MI_EXCEPTION,
         "mi_file_write() failed for newline!");
      return;
      }

   mi_file_close(fd);
   mi_free(msg_str); /* mi_lvarchar_to_string() allocated
                     * result
                     */
 
   return;
}