MATLAB: Detect New File in a Directory

detect new filedirectory

Hi All,
Last time when I google this question, I actually found a function that does what I need, but I couldn't find it this time.
Basically what I need is to monitor a directory for any new files. If there are new files, I will read the files in and continue to monitor for new files.
Any help will be greatly appreciated!
Thank you,
Lynniz

Best Answer

Hi lynniz,
You can use dir to list all the files under a certain directory, cache it and constantly query the folder and use setdiff to see whether a new file showed up. The following example shows a brief example. Note that I'm assuming everything underneath the directory is a regular file. If you have subdirectories, you can filter them out using the isdir field in the result of dir.
dir_content = dir;
filenames = {dir_content.name};
current_files = filenames;
while true
dir_content = dir;
filenames = {dir_content.name};
new_files = setdiff(filenames,current_files);
if ~isempty(new_files)
% deal with the new files
current_files = filenames;
else
fprintf('no new files\n')
end
end
Of course you may want to define an exit flag to get you out of the loop easily.
HTH