www.gusucode.com > MATLAB2008应用程序接口编程技术源码程序 > MATLAB2008应用程序接口编程技术源码程序/code/第8章/8.4/mexatexit.cpp
/* 程序段1 */ #include <stdio.h> #include <string.h> /* strlen */ #include "mex.h" /* 程序段2 */ /* Instantiate a static class constuctor */ class fileresource { public: fileresource() { fp=fopen("matlab.data","w");} ~fileresource() { fclose(fp);} FILE *fp; }; static fileresource file; /* 程序段3 */ void mexFunction(int nlhs,mxArray *[],int nrhs,const mxArray *prhs[]) { char *str; /* 程序段4 */ /* Check to be sure the file was opened correctly */ if(file.fp == NULL) { mexErrMsgTxt("Could not open matlab.data\n"); } /* 程序段5 */ /* Check for proper number of input and output arguments */ if (nrhs != 1) { mexErrMsgTxt("One input argument required."); } if (nlhs > 1) { mexErrMsgTxt("Too many output arguments."); } /* 程序段6 */ /* Check to be sure input is of type char */ if (!(mxIsChar(prhs[0]))) { mexErrMsgTxt("Input must be of type string.\n."); } /* 程序段7 */ /* The user passes a string in prhs[0]; write the string to the data file. NOTE: you must free str after it is used */ str=mxArrayToString(prhs[0]); if (static_cast<size_t>(fprintf(file.fp,"%s\n", str)) != strlen(str) +1){ mxFree(str); mexErrMsgTxt("Could not write data to file.\n"); } mexPrintf("Writing data to file.\n"); mxFree(str); return; }