Search code examples
matlabfile-existspause

Pausing MATLAB script until file is generated in directory


I have written a script which does the following: first it writes a text file to a specified directory, this text file is then called for a Post Processor via a PowerShell command which I also call in MATLAB in order to generate a result *.csv file. Lastly, the script formats the data in this generated *.csv file and plots the results.

The problem is that the script can only proceed once the given files have been placed in the directory - especially in the case of the *.csv file this may take 10-15 seconds. Currently I have simply added a sort of break point which prompts the user to wait, as follows:

fprintf("Check if *.csv is present in directory - then click 'Continue' \n")
keyboard;

I'm guessing there's a much better way to do this - ideally to run the script, automatically wait at a given point until a specified file is present in the directory, and then continue running the code.

How can I automate the check for existence of the *.csv file?


Solution

  • You can check if the file filename exist using isfile (post R2017b) like this:

    if isfile(filename)
         % File exists.
    else
         % File does not exist.
    end
    

    Pre R2017b you may use if exist(filename, 'file') == 2.

    You may combine this with a loop the following way:

    t_Start = tic;     % Start stopwatch timer (to set a maximum time)
    dt = 2;            % Check every dt seconds (example dt = 2)
    while isfile(filename) == false && toc(t_Start) < 60  % maximum 60 seconds
        pause(dt);
        time_counter = time_counter + dt;
    end
    
    % Continue with your code here.
    

    I'm using a while lopp to check if the file exist, and wait 2 seconds between each check. There is no reason to check every millisecond, unless you're in a hurry. You can of course change this.

    t_Start = tic; and toc(t_start) < 60 is a stopwatch that stops the loop after 60 seconds. Just using tic and toc < 60 works too, but that would reset a tic/toc call outside of the loop, if there are any.

    Note that isfile(filename) == false is the same as ~isfile(filename), but can be easier to read for beginners.