fclose() doesnt work

25 views (last 30 days)
Marc-Olivier Labrecque-Goulet
Edited: dpb on 1 Jun 2017
hi, I doing a very simple script to read data from a .txt file. Here is the only code in my script so far :
clc;
clear;
fid = fopen('fd.txt','r');
data = fscanf(fid,'%f');
fclose(fid);
But then, if I want to delete or change the name file it wont let me, it tell me the file is still open in matlab. Is it a bug or am I doing something wrong?
  1 Comment
Adam
Adam on 1 Jun 2017
Edited: Adam on 1 Jun 2017
Works fine when I try it with a newly created file. What is the output of fclose if you just put
fclose( fid )
without the semi-colon?
I have had occasions in the past though where Matlab seems to hold onto file handles after I had called fclose and I ended up doing an
fclose( 'all' )
which is not ideal.

Sign in to comment.

Answers (1)

dpb
dpb on 1 Jun 2017
Edited: dpb on 1 Jun 2017
Probably in your testing you have had an error or other misstep along the way in which you have overwritten the file handle variable fid for the file while it was still open and so the fclose operation is not operating on the correct fid.
You're not testing the return of fopen so you don't know that it has succeeded or you may have multiple connections to the same file open simultaneously.
As Adam notes, use fclose('all') to get back to ground zero and all will be well again. And, add the error-checking... :)
ADDENDUM
There are some other useful options in fopen for diagnosing such problems as well...
help fopen
...
fIDs = fopen('all') returns a row vector containing the file identifiers of
all open files. The identifiers reserved for standard input, output, and
error are not included. The number of elements in the vector is equal to
the number of open files.
filename = fopen(fileID) returns the file name that a previous call to
fopen used when it opened the file specified by fileID. The output
filename is resolved to the full path. The fopen function does not read
information from the file to determine the output value.
...

Tags

Community Treasure Hunt

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

Start Hunting!