help-octave
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Error while opening a .txt file


From: Markus Mützel
Subject: Re: Error while opening a .txt file
Date: Sun, 7 Jun 2020 14:46:58 +0200

Am 07. Juni 2020 um 14:37 Uhr schrieb "Andrew Janke":
> On 6/7/20 8:19 AM, Markus Mützel wrote:
> > Am 07. Juni 2020 um 14:13 Uhr schrieb "N":
> >> Would suggest the following so that file is closed before exit in case of 
> >> an error, as I remember there might be problems otherwise.
> >>
> >>
> >> [fid msg] = fopen('data.txt', 'r');                % Open file
> >> if(fid == -1)                                      % Error occured?
> >>   error(msg)                                         % Throw error and 
> >> show error messsage what went wrong
> >> end
> >>
> >> try                                                % Start try block so 
> >> that error could be catched and file closed
> >>   data = textscan (fid, '% f', 'HeaderLines', 5);
> >>   period_arr = data {1};
> >> catch err                                          % Catch error in case 
> >> it happen, rows below are not run then everything is OK
> >>   fclose(fid);                                       % This is needed 
> >> otherwise file is not closed then you make error in code and it is a 
> >> problem
> >>   rethrow(err)                                       % Rethrow the same 
> >> error but here file have been closed before error
> >> end
> >>
> >>
> >> Nicklas SB Karlsson
> >>
> > Consider using "unwind_protect" instead of "try", or the fid will only be 
> > closed if an error occurs.
> > Or remember to fclose(fid) after the catch-block.
> >
> > Markus
> >
> >
> >
> Or onCleanup! It can make your code really concise.
> 
> file = 'data.txt';
> [fid, msg] = fopen(file, 'r');
> if fid == -1
>   error('Failed opening file ''%s'': %s', file, msg);
> end
> RAII.fid = onCleanup(@() fclose(fid));  % automatically gets called when
> RAII is cleared
> data = textscan (fid, '% f', 'HeaderLines', 5);
> period_arr = data {1};
> % and that's it! no try/catch needed
> 
> Cheers,
> Andrew
> 

Or that.
But keep in mind that this might not work in scripts unless you explicitly 
clear the object returned by onCleanup when you are done.

Markus




reply via email to

[Prev in Thread] Current Thread [Next in Thread]