Max
Max

Reputation: 1481

Check existence of 'filename' in a chosen folder

I use

dir = uigetdir;

to ask the user for a foldername. In the next step, I want to make an if-else-statement, that checks if there is a file with a specific file name in that folder. A little bit like the following (not working) code:

if exist(dir/'filename','file')==true
  load([dir '/filename.mat']);
end

Upvotes: 0

Views: 1521

Answers (2)

il_raffa
il_raffa

Reputation: 5190

You should modify your code as follows:

%dir = uigetdir; Not to overload the "dir" command
sel_dir = uigetdir;

filename='my_file.mat'

if(exist(fullfile(sel_dir,filename),'file') == 2)
  load(fullfile(dir,filename));
else
   disp('file not found')
end

fullfile built-in function create the full pathname of your file.

Hope this helps.

Upvotes: 3

Alex Shesterov
Alex Shesterov

Reputation: 27555

Use strcat() to concatenate directory name and file name:

if exist(strcat(dir, '/filename.mat'), 'file')
  load(strcat(dir, '/filename.mat'));
end

Upvotes: 1

Related Questions