Why does fclose generates an ans return in the workspace?

조회 수: 5 (최근 30일)
Mats
Mats 2012년 9월 13일
Why does fclose() returns 'ans' in the workspace? If I change the line in status = flose(fid); the ans disappears and 'status' obviously appears. Why is flose() not suppressed?
directory = 'D:\Documents\MATLAB\Data\';
files = dir([directory,'*.nta']);
for iFile = 1:numel(files)
fid = fopen([directory,files(iFile).name]);
temp = textscan(fid,'%f %s %s %f %f %f %f %f', 'Delimiter', '\t', 'HeaderLines', 28);
fclose(fid);
end

답변 (2개)

Jan
Jan 2012년 9월 13일
편집: Jan 2012년 9월 13일
The output of fclose() is not suppressed, because there is no reason to suppress it. ans contains the uncaught output of the last processed command. Even from a MEX-function the first output can be replied even for nlhs==0 and the output appears in ans. The trailing semicolon suppresses the output to the command window.
Perhaps your problem gets clear, when you explain, what you want to achieve.
BTW, although I do not know a reason why fclose should fail, it is a good programming practice to catch the output in general to check for errors. I use this in larger functions:
fid = fclose(fid);
Then fid is set to 0 or -1 and a further usage is blocked. Example:
fid1 = fopen(File1);
fid2 = fopen(File2);
...
fid1 = fclose(File1);
fwrite(fid1, rand(10)); % Typo! It should be "fid2"! But error is caught.
Well, although this helps to write cleaner code, it is still not clean: The replied flag is a flag, which is only accidently an invalid file-ID. Better:
status = fclose(File1);
if status == -1, error...
A drawback of fid=fclose(fid) is that MLint warns about an unused variable, if fid is not used afterwards.

Titus Edelhofer
Titus Edelhofer 2012년 9월 13일
Hi,
that's because fclose returns a status. From the doc:
status = fclose(...) returns a status of 0 when the close operation is successful. Otherwise, it returns -1
And therefore there is nothing special about fclose: if you are not interested in the output of a function, use the ; ...
Titus
  댓글 수: 1
Titus Edelhofer
Titus Edelhofer 2012년 9월 13일
Sorry, read your post again: if you write
fclose(fid);
you should see no output either. But yes, you will generate an ans variable anyway.
Titus

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Variables에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by