How can I know which file identifiers correspond to open files?

29 次查看(过去 30 天)
I have opened a file using FOPEN and processed it. A few lines of code later, there was an error, and the file wasn't closed properly.
I would like to know which file identifiers correspond to open files so I can close them using FCLOSE.

采纳的回答

MathWorks Support Team
To see the list of identifiers of all open files you can use the following command:
fids = fopen('all')
To see the file names which correspond to those file identifiers you can use the following command:
filenames = arrayfun(@fopen, fids, 'UniformOutput', 0)
Finally, if you just want to close all open files you can use the following command:
fclose('all')

更多回答(1 个)

Josh Kahn
Josh Kahn 2023-6-9
编辑:Josh Kahn 2023-6-9
Also, if you want to avoid this, you can now use a cleanup object to close the file when the function is done (error or normal) similar to a try/catch.
For more information, see:
function myFunction
fid = fopen('myFile.txt', 'w')
cleanup = onCleanup(@() fclose(fid));
fprintf(fid, 'hello!');
end
equivalent to:
function myFunction
fid = fopen('myFile.txt', 'w')
try
fprintf(fid, 'hello!');
fclose(fid);
catch ME
fclose(fid);
rethrow(ME);
end
end

类别

Help CenterFile Exchange 中查找有关 Construct and Work with Object Arrays 的更多信息

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by