File: FileFromFolder.m

package info (click to toggle)
psychtoolbox-3 3.0.9%2Bsvn2579.dfsg1-1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 63,408 kB
  • sloc: ansic: 73,310; cpp: 11,139; objc: 3,129; sh: 1,669; python: 382; php: 272; makefile: 172; java: 113
file content (70 lines) | stat: -rw-r--r-- 2,174 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
function [file,nfile] = FileFromFolder(folder,mode,f_ext)
% [file,nfile] = FileFromFolder(folder,mode,ext)
%
% Returns struct with all files in directory FOLDER.
% MODE specifies whether an error is displayed when no directories are
% found (default). If MODE is 'silent', only a message will will be
% displayed in the command window. If left emtpy, default is implied.
% Ext is an optional filter on file extension. If specified, only files
% with the specified extension will be found. It can be a cell vector of
% strings for filtering on multiple extensions

% 2007 IH        Wrote it.
% 2007 IH&DN     Various additions
% 2008-08-06 DN  All file properties now in output struct
% 2009-02-14 DN  Now returns all files except '..' and '.', code
%                optimized
% 2010-05-26 DN  Got rid of for-loop, added optional filter on extension
% 2010-05-30 DN  Woops, some of the new changes break the function when no
%                files are found
% 2010-07-02 DN  Now supports filtering on multiple extensions
% 2010-07-12 DN  Fixed . at end of fname
% 2011-06-07 DN  Can now also filter for files with no extension

if nargin >= 2 && strcmp(mode,'silent')
    silent = true;
else
    silent = false;
end


file        = dir(folder);
file        = file(~[file.isdir]);  % get rid of folders. This also skips '..' and '.', which are marked as dirs

if ~isempty(file)
    % get file name and extension
    [name,ext]  = cellfun(@SplitFName,{file.name},'UniformOutput',false);
    [file.fname]= name{:};
    [file.ext]  = ext{:};

    % if filter, use it
    if nargin >= 3
        q_ext   = ismember(ext,f_ext);
        file    = file(q_ext);
    end
end

nfile       = length(file);

if nfile==0
    if silent
        fprintf('FileFromFolder: No files found in: %s\n',folder);
        file = [];
    elseif ~silent
        error('FileFromFolder: No files found in: %s',folder);
    end
end



% helpers
function [name,ext] = SplitFName(name)
% Look for EXTENSION part
ind = find(name == '.', 1, 'last');

if isempty(ind)
    ext = '';
else
    ext = name(ind+1:end);
    name(ind:end) = [];
end