Close open netcdf files
Show older comments
Short question:
Is there a way to explicitly close all open netcdf files, similar to
fclose('all')
for open binary files?
Longer explanation:
I'm currently running a series of simulations where data is saved time slice by time slice to netcdf files as the model integrates forward over time. Opening and closing files before and after each write is way too time-consuming, so I open all the files at the beginning of the simulation and close them at the end. No issues if everything runs smoothly, but if a simulation crashes mid-integration (which happens a few times per 100 simulations, due to numerical issues that are difficult to prevent) I'm left with a few hundred open file handles.
I currently deal with this via a lot of try/catch blocks in various parts of my code, and an onCleanup object, but I still once in a blue moon end up with some orphaned open files with no accessible NetCDF ID to use to close them (running a few hundred simulations in parallel, so it can be difficult to track down why these few instances escape my traps). At that point, the only way to solve the issue is a
clear all
which of course clears away much more than necessary (and also isn't really documented). Doing so leads to a warning message
Warning: Closing open netCDF file handles.
which seems to imply that there is a way, under the hood of clear, to recognize the presence of open file handles, and close them. Is that available without the accompanying wiping out of everything else in the workspace?
6 Comments
Star Strider
on 3 Jul 2014
The best way to get an answer is likely to Contact Support and report the inability to do a ‘close all’ on netCDF files as either a bug, and its eventual inclusion a request for an enhancement.
I did a thorough search of the documentation, FEX, and the Blogs (as I’m sure you did) and found nothing.
The answer about why clear generates the warning is probably the one given by John Evans here. If you had an infinite amount of free time, you could try to reverse engineer mexnc .. yet, I'd go for the support first ;-) who can probably forward your question to John if needed (edit: he doesn't seem to be working for TMW anymore).
Kelly Kearney
on 3 Jul 2014
An unsatisfying, yet all in all not that dirty, way to handle your issue in the short term could be to save all, clear all ( => "close the un-closable"), reload all.
Did I say "not that dirty"? .. well, blur my name please if you print this thread out!
David Ahrens
on 5 Oct 2017
Edited: David Ahrens
on 5 Oct 2017
Found that
clear mex
Works at closing left over file handles from netcdf calls.
Cedric
on 5 Oct 2017
Thanks David! I'm saving this thread with the feeling that it will be useful once.
Answers (0)
Categories
Find more on NetCDF in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!