First i will explain my situation. I have a folder that has a lot of sublevels and one of those subfolders contains the file i need. main folder subfolder1 subfolder1.1 subfolder1.1.1 subfolder1.1.2 subfolder1.1.3 File.sldd subfolder1.1.4 ... subfolder1.2 ... subfolder2 ... I know the name of the file: File.sldd But now I want to know the full path of the file so i can add this file to my current folder and open it with fopen(). The main folder is already added to my current folder. Is there a command that has the name of the file as input and gives me the path as output? Or is there a quick way to get the path of the file?
John Michell answered .
2025-11-20
function filefolder = findfile(root, filename)
dircontent = dir(fullfile(root, '*'));
if any(strcmpi({dircontent(~[dircontent.isdir]).name}, filename)) %case insensitive comparison. Works for Windows only.
%file is found in directory
filefolder = root;
else
%look in subdirectories
for subdir = dircontent([dircontent.isdir] & ~ismember({dircontent.name}, {'.', '..'}))'
filefolder = findfile(fullfile(root, subdir.name), filename);
if ~isempty(filefolder)
%found in a directory, all done
return;
end
end
%looked in all subdirectories and not found
filefolder = ''; %return empty
end
end
You can then do:
folder = findfile(mainfolder, 'File.sldd'); fid = fopen(fullfile(folder, 'File.sldd'));