fclose() doesnt work

26 visualizzazioni (ultimi 30 giorni)
Marc-Olivier Labrecque-Goulet
Modificato: dpb il 1 Giu 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 Commento
Adam
Adam il 1 Giu 2017
Modificato: Adam il 1 Giu 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.

Accedi per commentare.

Risposte (1)

dpb
dpb il 1 Giu 2017
Modificato: dpb il 1 Giu 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.
...

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by