How to return files with a specific extension using 'dir'?

1,771 views (last 30 days)
John on 11 Aug 2014
Commented: Stephen on 17 Aug 2021
The command
dir *.bmp
will print to the command window the names of all files in the current directory ending with the extension .bmp. I know the following is not valid MATLAB syntax, but is there a command that would be the equivalent of
fileList = dir *.bmp;
I want to create a list of all files ending with a specific extension using minimal code. Currently I have the following:
files = dir;
L = length(files);
index = false(1, L);
for k = 1:L
M = length(files(k).name);
if M > 4 && strcmp(files(k).name(M-3:M), '.bmp')
index(k) = true;
images = files(index);
There must be a simpler way. Thank you in advance for any comments.

Accepted Answer

Image Analyst
Image Analyst on 11 Aug 2014
fileList = dir('*.bmp');
Also, see the FAQ:, particulalry the second option.
Image Analyst
Image Analyst on 29 Apr 2020
True. But I don't think it's wise to have a folder with the name that a single image typically has. Virtually always, files the end in .bmp are image files, not folders.

Sign in to comment.

More Answers (1)

Tron on 27 Apr 2018
Old question, but I found another useful way of doing this. If you have a specific directory you want to search in, you can use a combination of dir and fullfile.
folder = uigetdir();
fileList = dir(fullfile(folder, '*.bmp'));

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!