我正在使用读取和处理结构化文件的函数:
fname=strcat(folder,'\',fname);
FID=fopen(fname);
% reading lines and digging and procsesing data using fgetl() and regexp()
fclose(FID);
当读取和挖掘部分出现任何错误时,将抛出错误消息,但文件已打开且FID指针丢失。它主要是由缺失或错误的线引起的。
如何在发生错误时避免丢失FID指针(用于手动关闭)和/或在发生错误时执行fclose(FID)
?
或者有没有办法打开一个文件而不用锁定它?
答案 0 :(得分:2)
也许使用try
-catch
块。事实上,你甚至不需要catch
:
fname = strcat(folder,'\',fname); %\\'
FID = fopen(fname);
try
%// reading lines and digging and procsesing data using fgetl() and regexp()
%// errors in this part are not shown
end
fclose(FID); %// this gets executed even if there were errors in reading and digging
或者,如果您想显示错误:
fname = strcat(folder,'\',fname); %\\'
FID = fopen(fname);
try
%// reading lines and digging and procsesing data using fgetl() and regexp()
catch
e = lasterror;
fprintf(2,'%s\n',e.message); %// show message in red
end
fclose(FID); %// this gets executed even if there were errors in reading and digging
或显示错误但首先关闭文件:
fname = strcat(folder,'\',fname); %\\'
FID = fopen(fname);
try
%// reading lines and digging and procsesing data using fgetl() and regexp()
catch ME
fclose(FID); %// close file
error(ME.message) %// issue error
end
fclose(FID);