Strange behavior retrieving directories' names with dir

조회 수: 2 (최근 30일)
Adriano
Adriano 2011년 9월 30일
I am trying to extract the names of the subdirectories contained in one directory. For example:
mainDirectory
matlabScript.m
results
subdirectory1
subdirectory2
subdirectory3
subdirectory4
I am running the following in matlabScript.m :
subdirectories = dir([pwd filesep results filesep]);
In theory, I should get a structure with 4 elements, one for each subdirectory. However, I am getting 6 elements. Of these, 4 are the desired subdirectories, but the other two are two mysterious subdirectories:
name: '.'
date: '30-sep-2011 10:09:14'
bytes: 0
isdir: 1
datenum: 7.3478e+005
name: '..'
date: '27-sep-2011 19:51:12'
bytes: 0
isdir: 1
datenum: 7.3477e+005
I am pretty sure I do not have this directories. I already read the documentation of dir ant nothing is stated. I also changed the OS properties to show any hidden folders and not even with that I found them. How can I correct this strange behavior? I am running MATLAB R2010b in a computer with Windows 7, 64 bits.
Thanks in advance

채택된 답변

Jan
Jan 2011년 9월 30일
Some modifications: cd is faster than pwd, the trailing file separator is not needed, fullfile is smarter than [cd, filesep, results], because it considers the already existing separator in e.g. "C:\":
subdirectories = dir(fullfile(cd, results));
If you want to exclude all files and folders starting with a dot -e.g. a common method under Unix:
subdirectories(strncmp({subdirectories.name}, '.', 1)) = [];
To remove only "." and "..":
subname = {subdirectories.name};
subname(strcmp(subname, '.')) = [];
subname(strcmp(subname, '..')) = [];
Although these two directories have been the first and second entries in the list in all of my tests under Windows95 to Windows7, Suse-Linux, MacOS7/8/9/X, AUX and AIX, I would not rely on this, but use astring comparison always.
  댓글 수: 1
Walter Roberson
Walter Roberson 2011년 9월 30일
The directory order is not defined by dir(), and depends upon the properties of the underlying file system. If the filesystem is one that does not happen to put . and .. first, then dir() will not return them as the first two entries.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Grzegorz Knor
Grzegorz Knor 2011년 9월 30일
This is not a strange behaviour:
. - is a current directory, type:
cd .
and .. is a parent directory, type:
cd ..
  댓글 수: 2
Grzegorz Knor
Grzegorz Knor 2011년 9월 30일
See also:
http://en.wikipedia.org/wiki/Path_%28computing%29
Adriano
Adriano 2011년 9월 30일
Thanks for your prompt answer! How could I correct this behavior in order to get only the 4 subdirectories I am interested in?

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 File Operations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by