dir
Lists the files and folders that match a name or pattern.
Category: Programming > Files and Folders
Syntax
dir
Displays the contents of the current folder.
dir(name)
Lists the items matching name, which can be a folder or a pattern with * wildcards.
d = dir(name)
Returns a struct array with one element per item.
Description
The result of a folder listing starts with the entries . and ... Use the isdir field to filter them out: d = d(~[d.isdir]) keeps only files. Collecting a field over the array with {d.name} gives a cell array of names, and [d.bytes] a numeric vector of sizes.
An item that does not exist produces an empty struct array with the same fields, so isempty(dir(name)) is a test for existence of a pattern.
Input arguments
name- Folder, file name or pattern such as
'data/*.csv'.
Output arguments
d- Struct array with fields
name,folder,date,bytes,isdiranddatenum.
Example
Listing files that match a pattern
mkdir data
writelines('1', 'data/x.txt');
writelines('22', 'data/y.csv');
d = dir('data/*.csv');
d.name
d.bytes
d.isdir
Output
ans = 'y.csv'
ans = 3
ans = logical
0