fclose() doesnt work
26 次查看(过去 30 天)
显示 更早的评论
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 个评论
Adam
2017-6-1
编辑:Adam
2017-6-1
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.
回答(1 个)
dpb
2017-6-1
编辑:dpb
2017-6-1
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.
...
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Low-Level File I/O 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!