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: Andrew Janke
Subject: Re: Error while opening a .txt file
Date: Sun, 7 Jun 2020 08:37:47 -0400
User-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:68.0) Gecko/20100101 Thunderbird/68.9.0


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



reply via email to

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