MATLAB Answers


Why do I receive the error "Inavlid file identifier" when using fopen?

Asked by Leah
on 9 Jul 2012
function spec = abc(filelist);
  fl = importdata(filelist);
    nFile = size(fl,1);
    %fid = fopen(file);
    Nbins = 1024;
    spec = zeros(nFile, Nbins);
    for iFile = 1:nFile
      % Read the 18 header text lines (but not the entire line, and discard)
      for i=1:18 hdr=textscan(fid,'%s %*[^\n]',1); end
      x = x{:,1};
      x = reshape(x,2,Nbins);
      spec(iFile,:) = x(2,:);

I get an error at fopen--I get the number -1 which is inccorect and i have no idea how to fix it. The error message is:

??? Error using ==> textscan
Invalid file identifier.  Use fopen to generate a valid file identifier.
Error in ==> rdUCS30MCA at 23
    for i=1:18 hdr=textscan(fid,'%s %*[^\n]',1);


Not nice, Leah. You found out that you cannot delete a thread after somebody has answered. Then you decided to overwrite the text by nonsense. This is a misuse of the idea of a public forum.

I restored the original question based on Lucas' assertion that this question might help others.

Sign in to comment.

2 Answers

Answer by Jan
on 10 Jul 2012

Every fopen() should be accompanied by a check of the results:

fid = fopen(fl{iFile});
if fid == -1
  error('Author:Function:OpenFile', 'Cannot open file: %s', fl{iFile});

File access is prone to problems. A stable program catchs them and the time wasted by debugging can be reduced, if an exhaustive error message is displayed.


Sign in to comment.

Answer by Image Analyst
on 9 Jul 2012

My guess would be that perhaps you didn't specify the folder in the list, and the files don't exist on the search path.


Sign in to comment.