Why does fclose generates an ans return in the workspace?

5 次查看(过去 30 天)
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 中查找有关 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