I am currently working on a simulation project where I want progress logs to be written to a file, so I can inspect them later. I was using diary for this. However having the setup of diary in the main function look ugly and made it bulky, so I wanted to move all the setup and diary functionality to a seperate function alike this:
function createLogFile(RunPath)
diaryfile = append(RunPath, 'log.txt');
if exist(diaryfile, 'file')
delete(diaryfile);
end
diary(diaryfile);
RAII.diary = onCleanup(@() diary('off'));
diary on
end
However as soon as the function finishes the diary falls out of scope and is closed.
Is there a way to pass the diary out of the function?

 採用された回答

Walter Roberson
Walter Roberson 2022 年 5 月 6 日

0 投票

Return RAII from the function. Your onCleanup will not fire until the struct stops existing.

4 件のコメント

Florian Rössing
Florian Rössing 2022 年 5 月 6 日
Thank you very much, that worked great. Could you tell me what this RAII objekct is? I found that code above in another matlab answer: https://de.mathworks.com/matlabcentral/answers/44117-close-diary-file-on-error
Walter Roberson
Walter Roberson 2022 年 5 月 6 日
You missed the part of that code that said
% ... now do whatever, and don't worry about closing the diary; it'll
% be automatically closed whenever this function returns for any reason...
That is, that code expected the action to be present at that location. That code is configured so that when the function shown is exited for whatever reason, that the diary would be closed.
In context, RAII is an arbitrary variable name. I have no idea what meaning "RAII" as a word had to the author of the code.
The key to that code is the onCleanup() call. When you call onCleanup then it creates a variable that has behavior attached to it, and the behavior attached is that when the variable is deleted, that the function will be run. If you return the value of the variable then the object will not be deleted until the returned value is deleted, postponing triggering running the function.
Florian Rössing
Florian Rössing 2022 年 5 月 9 日
Thanks for that nice explanation. I believed taht RAII was some kind of system object that specifically has this attribute. The oddly specific and strange name led me to believe that.
Walter Roberson
Walter Roberson 2022 年 5 月 9 日
https://en.cppreference.com/w/cpp/language/raii sounds plausible

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

製品

リリース

R2020b

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by