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:19:20 +0200

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




reply via email to

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