2015-02-10 148 views
1

我使用的功能,读取和处理结构化的文件整理脚本/函数执行:当错误发生时

fname=strcat(folder,'\',fname); 
FID=fopen(fname); 
% reading lines and digging and procsesing data using fgetl() and regexp() 
fclose(FID); 

当有任何错误阅读和挖掘部分的错误信息被抛出,但该文件是打开并且FID指针丢失。大部分是由于缺失或错误线路造成的。

发生错误时如何避免丢失FID指针(用于手动关闭)和/或发生错误时执行fclose(FID)? 或者有没有办法打开一个文件不锁定它?

回答

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); 
+0

如果在挖掘过程中有与创建的变量相关的命令,使用'try' ...'catch fclose(FID);返回; end'会强制执行停止并避免其他错误,对吧? – Crowley 2015-02-10 18:05:46

+0

我不确定我是否会在您的评论中忽略您的问题。 'try'块中的_first_错误导致执行转到'catch'部分。你是这个意思吗? – 2015-02-10 18:10:33

+0

是的。它应该正确关闭文件并终止进一步的执行,这将导致另一个错误。 – Crowley 2015-02-10 18:14:18