fgetl - still a valid function?

7 views (last 30 days)
Wesser
Wesser on 23 May 2022
Commented: Voss on 24 May 2022
I am trying to adapt someonelse's old (~2010) code for my use (run monte carlo of another program) . The old code uses the function "fgetl"
%READ HYDRUS OUTPUT FILES - This block reads for all the realizations of
%the Nod_inf.out file and stores the water content profiles for t=10 days in Prof_out table.
prof_out=zeros(101,num_sim+1);
for i=1:num_sim
fileID_out=fopen(strcat(path{i},'\nod_inf.out'));
skip_lines=123;
for k=1:(skip_lines)
x=fgetl(fileID_out);
end
temp=fscanf(fileID_out,'%f',[11,101])';
prof_out(:,i+1)=temp(:,4);
fclose(fileID_out);
end
prof_out(:,1)=temp(:,2);
But I keep getting the following error:
Error in fgetl (line 32)
[tline,lt] = fgets(fid);
Error in PAFBHydrusMC (line 144)
x=fgetl(fileID_out);
Why? I have double checked that it is writen with a lower case "L" and not the number 1... Thanks for any direction on this!

Accepted Answer

Voss
Voss on 23 May 2022
Edited: Voss on 23 May 2022
Yes, fgetl is still a valid built-in MATLAB function.
(Notice, the error message says, "error in fgetl (line 32)", so you know MATLAB is finding fgetl and getting to line 32 of it. If fgetl was no longer a valid function, you'd get an error message along the lines of "Unrecognized function or variable fgetl ...")
We'd have to see the rest of the error message to know for sure what the problem is, but it's most likely:
"Invalid file identifier. Use fopen to generate a valid file identifier."
If that is the case, it means that the file
strcat(path{i},'\nod_inf.out')
could not be opened for reading. Does the file exist?
Generally, every time you (or the person who wrote this code) use fopen, you should check that the file was successfully opened, and if not (in which case the file ID is -1) take an appropriate action (e.g., throw an error - fopen returns a message as its second output for you for this purpose - or just return from the function). For instance:
prof_out=zeros(101,num_sim+1);
for i=1:num_sim
file_name = strcat(path{i},'\nod_inf.out');
[fileID_out,err_msg] = fopen(file_name);
if fileID_out == -1
error('Could not open %s: %s',file_name,err_msg);
end
skip_lines=123;
for k=1:(skip_lines)
x=fgetl(fileID_out);
end
temp=fscanf(fileID_out,'%f',[11,101])';
prof_out(:,i+1)=temp(:,4);
fclose(fileID_out);
end
prof_out(:,1)=temp(:,2);
This prevents subsequent errors in fgetl or whatever file reading/writing function(s) are used, and lets you know the root cause of the problem right away.
  2 Comments
Voss
Voss on 24 May 2022
You're welcome!

Sign in to comment.

More Answers (0)

Products


Release

R2022a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!