MATLAB: Mex: How to read filepath from matlab-function

cfileMATLABmexopen filepath

Hello, i want to send from my matlab-function a path of a file to my mex-function. Then in my mex-function i want to open the file. Sorry for that quite simple question but i m quite a beginner in mex and c.
Heres my try to solve the problem. If someone could give me an advise how i could solve this i would be very grateful. Many thanks!
//In my matlab-script i call the mex-function like this:
data= myMex("c:\\testdata.dat");
//Then in my mex-file i try to use the argument filepath
mxChar *filename;
mxArray *xData;
FILE * pFile;
xData = prhs[0];
filename = mxGetChars(xData);
pFile= fopen(filename, "rb"); // result: file could not be opened

Best Answer

MATLAB stores strings as 2 bytes per "character", and they are not null terminated like in C. In your code above, filename points to the first "character" of the MATLAB string, 'c', but the other byte of that "character" on the MATLAB side is a 0, or null character, so filename is essentially just a single character 'c' as far as the C code and fopen is concerned. The actual characters in memory on the MATLAB side are:
'c' 0 ':' 0 '\' 0 '\' 0 't' 0 'e' 0 's' 0 't' 0 'd' 0 'a' 0 't' 0 'a' 0 '.' 0 'd' 0 'a' 0 't' 0
You need to convert this MATLAB version of a character string (2 bytes per character and not null terminated) to a C-style string (1 byte per character and null terminated). I generally prefer the mxArrayToString function because it does all this work for you. It will convert the above to this:
'c' ':' '\' '\' 't' 'e' 's' 't' 'd' 'a' 't' 'a' '.' 'd' 'a' 't' 0
E.g.,
#include <stdio.h>
#include "mex.h"
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
char *filename;
FILE * pFile;
if( nrhs != 1 || !mxIsChar(prhs[0]) ) {
mexErrMsgTxt("Need filename character string input.");
}
filename = mxArrayToString(prhs[0]);
pFile= fopen(filename, "rb");
mxFree(filename);
if( pFile == NULL ) {
mexErrMsgTxt("File did not open.");
}
// insert code to read the file, etc.
fclose(pFile);
}