confirm valid file identifier before flcose?

I am using GUI callbacks to close a file. Sometimes the file is aready closed, and I get an invalid file identifier error. Is there a robust way to check if the file is still open before calling fclose? I have tried using fopen('all') but that does not always catch it.

 採用された回答

Les Beckham
Les Beckham 2024 年 2 月 1 日

0 投票

If you call fopen on the file identifier when the file is closed it will return empty (instead of returning the filename). So, you can do this:
if ~isempty(fopen(fid))
fclose(fid);
end

その他の回答 (2 件)

Voss
Voss 2024 年 2 月 1 日

0 投票

try
fclose(fid);
catch
% file already closed, do nothing
end
CM
CM 2024 年 2 月 2 日

0 投票

Thanks Les and Voss. I have actually combined both techniques, with the try inside the if loop. I am not using multithreading, so I am not sure if it is possible for the fid to become invalid within the space of the fopen and the if statements, but I have been going round in circles on this for a while and want to make sure it is robust.

カテゴリ

ヘルプ センター および File ExchangeEntering Commands についてさらに検索

タグ

質問済み:

CM
2024 年 2 月 1 日

回答済み:

CM
2024 年 2 月 2 日

Community Treasure Hunt

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

Start Hunting!

Translated by