Text File I/O Question

조회 수: 7 (최근 30일)
Berk Öztürk
Berk Öztürk 2022년 12월 26일
댓글: Voss 2022년 12월 27일
Question : 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..." ,
charnum = char_counter('simple.txt,'a')
charnum =
3
My code is below and passed all tests but I want to know if there is a pitfall in my code or a way to do it smarter. Thanks in advance.
function charnum = char_counter(fname,character)
charnum = 0;
if ischar(character)==0
charnum=-1;
return;
end
fid=fopen(fname,'rt');
if fid<0
charnum = -1;
return;
end
oneline = fgets(fid);
while ischar(oneline)
for ii=1:length(oneline)
if oneline(ii)==character
charnum = charnum + 1;
else
continue;
end
end
oneline = fgets(fid);
end
fclose(fid);
  댓글 수: 1
Voss
Voss 2022년 12월 27일
The
else
continue;
block is unnecessary.

댓글을 달려면 로그인하십시오.

채택된 답변

Voss
Voss 2022년 12월 26일
You don't need to go line-by-line and character-by-character, you can read the entire file at once and count the total number of occurrences of character like this:
charnum = nnz(fread(fid,'*char') == character);
If you do that, your function might look something like this:
function charnum = char_counter(fname,character)
if ~ischar(character) || ~isscalar(character)
charnum = -1;
return
end
fid = fopen(fname,'rt');
if fid < 0
charnum = -1;
return
end
charnum = nnz(fread(fid,'*char') == character);
fclose(fid);

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Import and Export에 대해 자세히 알아보기

제품


릴리스

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by