Closing up opened files

In this example, we shall see how to close an opened file once the function accessing it, is completely executed.

Matlab




function geeks
    file = fopen("data.txt","r");
    %creating the cleanup object which
    %will close the opened file safely
    %once the main function is executed
    cleanob = onCleanup(@()fclose(file));
end


In the above function, we create a file object which holds the ‘data.txt’ file in read only mode. Then, we create a cleanup object which calls the oncleanUp function with the anonymous function handle that closes the opened file once the geeks function’s execution is completed. 

The point to be noted here is that it does not matter where the onCleanup object is initialized in the function; MATLAB will always execute in the end of function execution, which makes the onCleanup function highly useful, in case the user needs to run some tasks in the end of the function execution(which we shall see in the next example).

Output:

 

As it can be seen, the function executes without any error, which confirms that the file has been closed safely.

Clean Up When Functions Complete in MATLAB

While working in MATLAB, handling the workspaces is crucial for the proper working of multiple scripts and functions. That is why it is a healthy habit to clean up the MATLAB workspace once a function execution is completed.

Some of the requirements for performing a cleanup routine, cleaning up all the files, scripts, and/or functions of the last work environment, could be:

  • Removing all the variables from workspace that are not required.
  • Freeing up any used memory.
  • Removing locks placed upon any file in the MATLAB session.
  • Restoration of the MATLAB path, if it was tempered with.
  • Close any files (scripts or functions) that were opened for access.

In this article, we shall use the onCleanup function of MATLAB to perform different sorts of cleanup tasks in MATLAB.

Syntax

The cleanup function takes a function handle as its input argument, which is performed when MATLAB picks up a cleanup object.

cleanUpObj = onCleanup(function_handle)

The input function handle could be an anonymous function, which generally is the case and executes the input handle once the function containing the onCleanup object is read into the memory.

Now we shall see some uses of the onCleanup function with example.

Similar Reads

Closing up opened files

In this example, we shall see how to close an opened file once the function accessing it, is completely executed....

Scheduling Task at the End of Function Execution

...

Conclusion

As explained earlier as well, the onCleanup object is always executed upon the function completion, irrespective of its declaration. This property can be used to schedule certain tasks at the end of function execution but, the same task can be constructed as the onCleanup object at anytime in the function definition. See the following example....