core/matlab/examples/mex/mexatexit.c

00001 /*=================================================================
00002  * mexatexit.c 
00003  * 
00004  * This example demonstrates how to use mexAtExit.  It allows you to
00005  * write strings to a data file, matlab.data.  The MEX-file
00006  * mexatexit.c registers an exit function that closes the datafile.
00007  * The input to the MEX-file mexatexit is a string.  You may continue
00008  * calling the function with new strings to add to the file
00009  * matlab.data. The data file will not be closed until the MEX-file is
00010  * cleared or MATLAB is exited, which cause the exit function to be
00011  * executed.
00012 
00013  * This is a MEX-file for MATLAB.  
00014  * Copyright 1984-2006 The MathWorks, Inc.
00015  * All rights reserved.
00016  *=================================================================*/
00017 
00018 /* $Revision: 1.1 $ */
00019 
00020 #include <stdio.h>
00021 #include <string.h> /* strlen */
00022 #include "mex.h"
00023 
00024 static FILE  *fp=NULL;
00025 
00026 /* Here is the exit function, which gets run when the MEX-file is
00027    cleared and when the user exits MATLAB. The mexAtExit function
00028    should always be declared as static. */
00029 static void CloseStream(void)
00030 {
00031   mexPrintf("Closing file matlab.data.\n");
00032   fclose(fp);
00033 }
00034 
00035 void 
00036 mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[])
00037 {
00038     char *str;
00039     (void) plhs;      /* unused parameter */
00040 
00041     /* Check for proper number of input and output arguments */    
00042     if (nrhs != 1) {
00043     mexErrMsgTxt("One input argument required.");
00044     } 
00045     if(nlhs > 1){
00046     mexErrMsgTxt("Too many output arguments.");
00047     }
00048     if (!(mxIsChar(prhs[0]))){
00049     mexErrMsgTxt("Input must be of type string.\n.");
00050     }
00051     
00052     if (fp==NULL){
00053     fp = fopen("matlab.data", "w");
00054     if (fp == NULL){
00055         mexErrMsgTxt("Could not open file matlab.data."); 
00056     }
00057     mexPrintf("Opening file matlab.data.\n");
00058     
00059     /* Register an exit function. You should only register the
00060        exit function after the file has been opened successfully*/
00061     mexAtExit(CloseStream);
00062     }
00063     /* The user passes a string in prhs[0]; write the string
00064        to the data file. NOTE: you must free str after it is used */ 
00065     str=mxArrayToString(prhs[0]);
00066     if ((size_t)fprintf(fp,"%s\n", str) != strlen(str) +1){
00067     mxFree(str);
00068     mexErrMsgTxt("Could not write data to file.\n");
00069     }
00070     mexPrintf("Writing data to file.\n");
00071     mxFree(str);
00072 } 

GridLAB-DTM Version 1.0
An open-source project initiated by the US Department of Energy