21 views (last 30 days)

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. As an example, consider the following run. The file "simple.txt" contains a single line: "This file should have exactly three a-s...

function charnum=char_counter(fname,a)

fid=fopen(fname,'rt');

if fid<0

charnum=-1;

fprintf('error\n');

return;

end

if ischar('a')==0

return;

end

if fid>0 && ischar(a)

line=fgets(fid);

n=0;

for n=n+count(line,a)

end

charnum=n;

else charnum=-1;

end

if ischar(a)==0

charnum =-1;

elseif charnum==0

charnum=0;

return;

end

fclose(fid);

why second error is coming?

Opportunities for recent engineering grads.

Apply Today
## 6 Comments

## Direct link to this comment

https://es.mathworks.com/matlabcentral/answers/476673-week-9-assignment-2#comment_736659

⋮## Direct link to this comment

https://es.mathworks.com/matlabcentral/answers/476673-week-9-assignment-2#comment_736659

## Direct link to this comment

https://es.mathworks.com/matlabcentral/answers/476673-week-9-assignment-2#comment_736665

⋮## Direct link to this comment

https://es.mathworks.com/matlabcentral/answers/476673-week-9-assignment-2#comment_736665

## Direct link to this comment

https://es.mathworks.com/matlabcentral/answers/476673-week-9-assignment-2#comment_736674

⋮## Direct link to this comment

https://es.mathworks.com/matlabcentral/answers/476673-week-9-assignment-2#comment_736674

## Direct link to this comment

https://es.mathworks.com/matlabcentral/answers/476673-week-9-assignment-2#comment_736690

⋮## Direct link to this comment

https://es.mathworks.com/matlabcentral/answers/476673-week-9-assignment-2#comment_736690

## Direct link to this comment

https://es.mathworks.com/matlabcentral/answers/476673-week-9-assignment-2#comment_736692

⋮## Direct link to this comment

https://es.mathworks.com/matlabcentral/answers/476673-week-9-assignment-2#comment_736692

## Direct link to this comment

https://es.mathworks.com/matlabcentral/answers/476673-week-9-assignment-2#comment_736723

⋮## Direct link to this comment

https://es.mathworks.com/matlabcentral/answers/476673-week-9-assignment-2#comment_736723

Sign in to comment.