필터 지우기
필터 지우기

Mex: How to read filepath from matlab-function?

조회 수: 2 (최근 30일)
mick strife
mick strife 2013년 4월 21일
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

채택된 답변

James Tursa
James Tursa 2013년 4월 26일
편집: James Tursa 2013년 4월 26일
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
mick strife
mick strife 2013년 5월 1일
Thx james! i really appreciate your effort :)

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Write C Functions Callable from MATLAB (MEX Files)에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by