MATLAB: ‘exist’ function returning false positive for directory.

absolutedirectoryexistfileMATLABpath

I'm trying to check if a file/directory path is valid before using it. I've seen countless examples of the 'exist' command to check to see if the argument is real, but I've found that MATLAB lies to you if you if the directory is somewhere on the path, but not accessible.
Consider the following example.
cd C:/
mkdir a; cd a
mkdir b; cd b
mkdir c; cd c
% Now current directory is C:/a/b/c
% I'm given an input dir called "b/c"
exist('b/c','dir') % Returns 7 - Indicating that "directory does exist"
% Thinking that's a real directory, I attempt to access it and get an error.
cd b/c
%:: Error using cd
%:: Cannot CD to C:\a\b\c\b\c (Name is nonexistent or not a directory).
What alternatives to 'exist' are there to correctly identify the existence of a folder or file if and only if:
  • the absolute path, relative to '/' or 'C:', exists, or
  • the relative path, from the current directory, exists?
I could try shelling out to cmd, but that seems hacky:
system('IF EXIST b/c (exit /B 1) ELSE (exit /B 0)')
Any suggestions?

Best Answer

Since R2017b the command isfolder is available and safer than exist('dir').
A problem of your approach is the usage of relative path names. Remember that a GUI or TIMER callback can change the current directory unexpectedly. In parallel programming this is a common problem also. So the solution is easy: Never work with relative paths.
A clean version:
base = 'C:\';
mkdir(fullfile(base, 'a', 'b', 'c');
want = 'C:/a/b/c';
isfolder(fullfile(want, 'b\c')) % FALSE

isfolder(fullfile(base, 'b\c')) % FALSE
Note, that any crazy callback cannot cofuse this by changing the current directory.
If do not understand, why exist('b/c','dir') returns 7, if the current folder is C:\a\b\c . Maybe b\c is existing anywhere in Matlab's path ? Remember that exist checks the complete path.
By the way, why do you assume, that
mkdir a; cd a
creates 'C:\a' and not the directory 'C:\a; cd a'
? It works as you expect it, but I do not know, where this is documented.