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: N
Subject: Re: Error while opening a .txt file
Date: Sun, 7 Jun 2020 14:13:49 +0200

> Am 07. Juni 2020 um 11:36 Uhr schrieb "Ganesh Kini":
> > Hi i was trying to run this code for the first time
>
> > fid = fopen ('data.txt');
> > data = textscan (fid, '% f', 'HeaderLines', 5);
> > period_arr = data {1};
> > fclose (fid);
>
> > error
> > >> test
> > Error using textscan
> > Invalid file identifier. Use fopen to generate a valid file identifier.
>
> > Error in test (line 2)
> > data = textscan (fid, '% f', 'HeaderLines', 5);
>
> >
> > Please help me

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



reply via email to

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