fgetl gets stuck in infinite loop
5 views (last 30 days)
Show older comments
Hi,
I am new to programming and have an issue with my simulation (I 'inherited' the code). When I run the simulation, sometimes works ok, but sometimes it just stops (I don't get an error, but simulation is not proceeding). When I terminate simulation (ctr+c) I get an notification that tells me it stoped in fgetl(line 33). (see the sctreen shot)

I tried pausing and restarting the simulation, terminating it and restarting (sometimes that works, sometimes it stops again, but not in the same step), restarting comupter ...
Does anyone have an idea what is going on? I'm using MATLAB R2016a.
Here is a code of the program that 'error' occurs:
function getmcml2(name, Nz,Nr)
% function getmcml2(name)
global Rd Rr Rsp Td A Azr Az
fid = fopen(name,'r');
line = fgetl(fid);
while(isempty(strfind(line,'RAT')))
line = fgetl(fid);
end
line = fgetl(fid);
while(isempty(strfind(line,'RAT')))
line = fgetl(fid);
end
line = fgetl(fid);
Rsp = sscanf(line,'%f'); %disp(sprintf('\tRsp = %f', Rsp))
line = fgetl(fid);
Rd = sscanf(line,'%f'); %disp(sprintf('\tRd = %f', Rd))
line = fgetl(fid);
A = sscanf(line,'%f'); %disp(sprintf('\tA = %f', A))
line = fgetl(fid);
Td = sscanf(line,'%f'); %disp(sprintf('\tT = %f', Td))
while(isempty(strfind(line,'A_z')))
line = fgetl(fid);
end
Az = fscanf(fid,'%f');
while(isempty(strfind(line,'Rd_r')))
line = fgetl(fid);
end
Rr = fscanf(fid,'%f');
while(isempty(strfind(line,'A_rz')))
line = fgetl(fid);
end
u = fscanf(fid,'%f');
Azr = reshape(u, [Nz Nr]);
fclose(fid);
clear fid
5 Comments
Answers (1)
Jan
on 5 Feb 2021
while(isempty(strfind(line,'A_z')))
line = fgetl(fid);
end
This code stucks in an infinite loop, if a file does not contain the substring 'A_z' in the expected location.
A safer method to search for a string:
try
...
key = 'A_z';
while ~contains(line, key)
line = fgetl(fid);
end
Az = fscanf(fid,'%f');
key = 'Rd_r';
while ~contains(line, key)
line = fgetl(fid);
end
Rr = fscanf(fid,'%f');
...
catch ME
error(['Tools:', mfilename, ':BadFile'], 'Failed to find [%s] in: %s', key, name);
end
By the way, it is a fragile programming style to provide the outputs using global variabels. Prefer to use output arguments instead. Remember, that any other program, which uses global variables with hte same name, will be deeply confused.
Hint: fgets ist faster than fgetl, which calls fgets internally and spends time to crop the line break.
Using clear to remove variabels is a waste of time in Matlab in most cases.
See Also
Categories
Find more on Entering Commands in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!