Why does fclose generates an ans return in the workspace?
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
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
0 comentarios
Respuestas (2)
Jan
el 13 de Sept. de 2012
Editada: Jan
el 13 de Sept. de 2012
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.
0 comentarios
Titus Edelhofer
el 13 de Sept. de 2012
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 comentario
Titus Edelhofer
el 13 de Sept. de 2012
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
Ver también
Categorías
Más información sobre Low-Level File I/O en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!