Text file I/O
Show older comments
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,character)
fid = fopen(fname,'rt') %gets the file
z=0;
charnum=0;
if fid < 0 || ~ischar(character) %checks if its valid, but I don't know how to return an "-1" if file missing
charnum=-1
end
escrito = fgets(fid)
for i=1:length(escrito)
z=z+1;
if escrito(z)==char(character) %Here I check every position of the text to see if it's equal to the character
charnum=charnum+1; %It sums everytime it happens
end
end
charnum %returns the sum
fprintf('\n');
fclose(fid);
end
The code works in the basic files, but fails at:
"Test with all visible characters
Variable charnum has an incorrect value. When testing with ' ' your solution returned 1 which is incorrect. (75444)"
And the "Non existent file" thing
Accepted Answer
More Answers (0)
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!