error using fprintf invalid file identifier use fopen .this code runs well on computer but not on laptop why?tell me why it is happen

1 view (last 30 days)
fid = fopen('noPlate.txt', 'w'); % This portion of code writes the number plate
fprintf(fid,'%s\n',noPlate); % to the text file, if executed a notepad file with the
fclose(fid); % name noPlate.txt will be open with the number plate written.
winopen('noPlate.txt')
  3 Comments

Sign in to comment.

Answers (3)

Stephen23
Stephen23 on 6 May 2015
Edited: Stephen23 on 6 May 2015
It is most likely that fopen is not successfully creating a file, so the value of fid is not a valid file identifier, and thus fprintf throws this error. But to know for sure you will have to tell us what the values of fid is:
disp(fid)
It is possible that the file might already exist but be write-protected, or the user may not have write-rights for that directory... there are many reasons why fopen may fail to create a file. Please tell us the fid value!
  3 Comments
Stephen23
Stephen23 on 7 May 2015
Edited: Stephen23 on 8 May 2015
When you read the documentation it clearly states the an fid value of -1 means that fopen cannot create the file. So there must be something preventing MATLAB from creating or accessing that location:
  • the disc is full
  • the directory does not exist
  • the directory is protected somehow
  • the path has non-ASCII characters
  • you did not fclose the file on a previous loop
  • the file already exists and is read-only
  • The file is open in another program
  • or something else similar...

Sign in to comment.


Star Strider
Star Strider on 6 May 2015
Your fopen call worked for me (in R2015a). Remove the semicolon at the end of the line and see if it successfully created the file. The value for ‘fid’ should produce an integer >=3. If it’s -1, that means it failed to create the file for some reason.
  1 Comment
Star Strider
Star Strider on 7 May 2015
To see the files you have open, see the relevant fopen documentation, specifically Get Information About Open Files. You can also find the file name of the open files (same section of the documentation).
That should tell you if you have a file of the same name open, preventing you from opening it again.

Sign in to comment.


Guillaume
Guillaume on 7 May 2015
The solution is for you to find why you can't create the file. Have you got write permission to the current directory (you can see which directory is current with pwd)? Maybe the file already exists and is marked as read-only.
Another strong possibility, you've created the file with fopen on a previous attempt and never fclose'd it. In which case, restarting matlab should cure the problem (or use a different filename).

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!