core/matlab/examples/mex/mexatexit.cpp

00001 /*=================================================================
00002  * mexatexit.cpp 
00003  * 
00004  * This example is the C++ version of mexatexit.c.  It demonstrates
00005  * how to write strings to a data file using a C++ static class
00006  * contructor.  In this example, we do not need to use a mexatexit
00007  * function to close the data file. This is because in C++ when you
00008  * instantiate a static class constructor, the destructor for that
00009  * static class gets called automatically when the MEX-file is cleared
00010  * or exited.  
00011  *
00012  * The input to the MEX-file is a string.  You may continue calling
00013  * the function with new strings to add to the data file
00014  * matlab.data. The data file will not be closed until the MEX-file is
00015  * cleared or MATLAB is exited.
00016 
00017  * This is a MEX-file for MATLAB.  
00018  * Copyright 1984-2006 The MathWorks, Inc.
00019  * All rights reserved.
00020  *=================================================================*/
00021 
00022 /* $Revision: 1.1 $ */
00023 
00024 #include <stdio.h>
00025 #include <string.h> /* strlen */
00026 #include "mex.h"
00027 
00028 /* Instantiate a static class constuctor */
00029 class fileresource {
00030 public:
00031   fileresource() { fp=fopen("matlab.data","w");}
00032   ~fileresource() { fclose(fp);}
00033   FILE *fp;
00034 };
00035 
00036 static fileresource file;
00037 
00038 void 
00039 mexFunction(int nlhs,mxArray *[],int nrhs,const mxArray *prhs[])
00040 {
00041     char *str;
00042     
00043     /* Check to be sure the file was opened correctly */
00044     if(file.fp == NULL){
00045     mexErrMsgTxt("Could not open matlab.data\n");
00046     }
00047 
00048     /* Check for proper number of input and output arguments */    
00049     if (nrhs != 1) {
00050     mexErrMsgTxt("One input argument required.");
00051     } 
00052     if (nlhs > 1){
00053     mexErrMsgTxt("Too many output arguments.");
00054     }
00055     
00056     /* Check to be sure input is of type char */
00057     if (!(mxIsChar(prhs[0]))){
00058     mexErrMsgTxt("Input must be of type string.\n.");
00059     }
00060     
00061     /* The user passes a string in prhs[0]; write the string
00062        to the data file. NOTE: you must free str after it is used */ 
00063     str=mxArrayToString(prhs[0]);
00064     if (static_cast<size_t>(fprintf(file.fp,"%s\n", str)) != strlen(str) +1){
00065     mxFree(str);
00066     mexErrMsgTxt("Could not write data to file.\n");
00067     }
00068     mexPrintf("Writing data to file.\n");
00069     mxFree(str);
00070     return;
00071 }

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