Running a function for each file in Octave

Often if you have a directory of data files, you want to run a processing or parsing function for every file in that directory.

This snippet allows you to select files using a glob pattern (e.g. data/*.txt)


% Run func(filepath, fileId) for each file and fclose() it afterwards
% Usage example: runForEachFile(@parseTXT, "data/*.txt")
function runForEachFile(func, pattern)
  files = glob(pattern);
  for i = 1:numel(files)
    file = files{i};
    % Open file...
    fid = fopen(file);
    % Run function
    func(file, fid);
    % Cleanup

Usage example:

% Define utility handler function to only display the filename
function dispFirst(x, y) disp(x) endfunction

% Essentially displays a list of filenames,
% with the opened files being ignored by dispFirst.
% Opens only one file at a time!
runForEachFile(@dispFirst, "data/*.txt")