Effacer les filtres
Effacer les filtres

Mex: How to read filepath from matlab-function?

2 vues (au cours des 30 derniers jours)
mick strife
mick strife le 21 Avr 2013
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

Réponse acceptée

James Tursa
James Tursa le 26 Avr 2013
Modifié(e) : James Tursa le 26 Avr 2013
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);
}
  1 commentaire
mick strife
mick strife le 1 Mai 2013
Thx james! i really appreciate your effort :)

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Write C Functions Callable from MATLAB (MEX Files) dans Help Center et File Exchange

Produits

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by