フィルターのクリア

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 Center および File ExchangeWrite 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