fclose() doesnt work

조회 수: 25 (최근 30일)
Marc-Olivier Labrecque-Goulet
Marc-Olivier Labrecque-Goulet 2017년 6월 1일
편집: dpb 2017년 6월 1일
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
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
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.
...

카테고리

Help CenterFile 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!

Translated by