I am unable to understand what's wrong in this code.

Write a function called char_counter that counts the number of a certain character in a text file. The function takes two input arguments, fname, a char vector of the filename and character, the char it counts in the file. The function returns charnum, the number of characters found. If the file is not found or character is not a valid char, the function return -1.
I am unable to pass 2 out of 4 assessment which includes 'Invalid input' and 'Non existent file'. What wrong it this code?
function charnum = char_counter(fname, character)
fid = fopen(fname, 'r');
x = 0;
if fid < 0 || ~ischar(character)
fprintf('-1');
return
end
lines = fgets(fid);
while ischar(lines)
for i = 1:length(lines)
if lines(i) == character
x = x + 1;
end
end
lines = fgets(fid);
end
charnum = x;
fclose(fid);

Answers (1)

if fid < 0 || ~ischar(character)
fprintf('-1');
charnum=-1;
return
end

1 Comment

To avoid leaving fid un-closed, it is beter to separate the condictions
if ~ischar(character)
charnum=-1;
return
end
fid = fopen(fname, 'r');
if fid < 0
charnum=-1;
return
end

Sign in to comment.

Tags

Asked:

on 30 Jun 2023

Commented:

on 30 Jun 2023

Community Treasure Hunt

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

Start Hunting!