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

30 ビュー (過去 30 日間)
MathWorks Support Team
MathWorks Support Team 2009 年 11 月 13 日
編集済み: Josh Kahn 2023 年 6 月 9 日
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
MathWorks Support Team 2009 年 11 月 13 日
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 Center および File ExchangeConstruct 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