Linux Matlab - is it possible to determine whether a directory is a link?

4 次查看(过去 30 天)
I wrote a simple Matlab script using "dir" to recursively follow directories in a linux environment. The only thing is I don't want to follow linked directories. Does Matlab have a way of figuring out which directories are linked directories? On my Linux window, linked dirs show up as
/dir_x -> /home/some_directory_path/some_other_path/
rather than just /dir_x

采纳的回答

Lorenzo Luengo
Lorenzo Luengo 2011-7-8
Try somthing like
[a,b]=system('ls -l /tmp/myfile | cut -c 1')
if b is an 'l' (ell), then /tmp/myfile is a link, if it's a 'd' then it's a regular directory. There are some other special types like 's','p','b','c' but most common are 'd' and 'l'.
Another way can be
[a,b]=system('stat -c ''%F'' /tmp/DELETEME')
If 'b' says 'symbolic link' there you got it, if it says 'directory', it is a directory.
Just another tip. Beware of newlines that may be at the end of b. I usually get rid of them piping the output through an
tr -d '[\r\n]'
at the end of the command. strtrim function is also handy. Regards!

更多回答(1 个)

Jan
Jan 2011-7-8
I assume you need a Mex function, which calls stat and uses the non-Posix macro S_ISLNK. See: http://www.mitchr.me/SS/exampleCode/AUPG/fileData.c.html But it is not trivial to consider Unicode file names, see: Answers: Matlab string to wchar under linux and CSSM: 301249.
I cannot test this under linux - perhaps you need further headers:
#include "mex.h"
#include <sys\stat.h>
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
char *FileName;
struct stat S;
// Check number and type of arguments:
if (nrhs != 1) {
mexErrMsgTxt("*** FileIsLink[mex]: 1 input required.");
}
if (nlhs > 1) {
mexErrMsgTxt("*** FileIsLink[mex]: 1 output allowed.");
}
// Type of input arguments:
if (!mxIsChar(prhs[0])) {
mexErrMsgTxt("*** FileIsLink[mex]: 1st input must be the file name.");
}
// Obtain FileName:
if ((FileName = mxArrayToString(prhs[0])) == NULL) {
mexErrMsgTxt("*** FileIsLink[mex]: "
"Cannot convert FileName to C-string.");
}
// Get the status and create output:
if (stat(FileName, &S) == 0) {
plhs[0] = mxCreateLogicalScalar((mxLogical) S_ISLNK(s.st_mode));
} else { // File not found:
plhs[0] = mxCreateDoubleMatrix(0, 0, mxREAL);
}
mxFree(FileName);
return;
}

类别

Help CenterFile Exchange 中查找有关 Introduction to Installation and Licensing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by