Using MATLAB, I need to extract an array of "valid" files from a directory. By valid, I mean they must not be a directory and they must not be a hidden file. Filtering out directories is easy enough because the structure that dir
returns has a field called isDir. However I also need to filter out hidden files that MacOSX or Windows might put in the directory. What is the easiest cross-platform way to do this? I don't really understand how hidden files work.
Asked
Active
Viewed 6,351 times
4

JnBrymn
- 24,245
- 28
- 105
- 147
-
2No Matlab expert, but this is how hidden files work: on Mac OS X (and other Unix systems), their name starts with a period (`.`). On Windows, their "hidden" attribute is set. Windows hidden files are only hidden on a Windows filesystem, i.e. FAT or NTFS. – Fred Foo Mar 08 '11 at 15:18
2 Answers
5
Assuming all hidden files start with '.'. Here is a shortcut to remove them:
s = dir(target); % 'target' is the investigated directory
%remove hidden files
s = s(arrayfun(@(x) ~strcmp(x.name(1),'.'),s))

dumbfingers
- 7,001
- 5
- 54
- 80

Amit Joshi
- 51
- 1
- 1
5
You can combine DIR and FILEATTRIB to check for hidden files.
folder = uigetdir('please choose directory');
fileList = dir(folder);
%# remove all folders
isBadFile = cat(1,fileList.isdir); %# all directories are bad
%# loop to identify hidden files
for iFile = find(~isBadFile)' %'# loop only non-dirs
%# on OSX, hidden files start with a dot
isBadFile(iFile) = strcmp(fileList(iFile).name(1),'.');
if ~isBadFile(iFile) && ispc
%# check for hidden Windows files - only works on Windows
[~,stats] = fileattrib(fullfile(folder,fileList(iFile).name));
if stats.hidden
isBadFile(iFile) = true;
end
end
end
%# remove bad files
fileList(isBadFile) = [];
-
@gnovice: Thanks for the fix. Ah, copy-paste-forget, bane of my existence! – Jonas Mar 08 '11 at 16:41
-
Out of curiosity, is the `[~,out] = something()` syntax legal on some later version than I'm using? I usually call `~` as `trash` - but it still makes the assignment. – JnBrymn Mar 10 '11 at 12:24
-
@John Berryman: Yes, this has been legal since 2008x, if I recall correctly. The `~` assigns the output to nothing. – Jonas Mar 10 '11 at 12:43
-
1The first two entries might not be . and .. - for instance if you have an Emacs temporary file starting with a # that will come first. – Brian Burns Sep 18 '11 at 20:34