display file function crash

조회 수: 7 (최근 30일)
Yu Liu
Yu Liu 2019년 10월 20일
댓글: Yu Liu 2019년 10월 22일
%I want to display a file and according to the book, I wrote the display file function like below, but it always showed that 'something wrong happen'. I have no idea which I part I did the wrong programming.%
function DisplayFile(filename)
try
fid=fopen(filename);
if fid == -1
disp(sprintf('Unable to open file ''%s'' ',filename));
else
while ~feof(fid)
tline = fget1(fid);
disp(tline);
end
fclose(fid);
end
catch
fclose(fid);
disp('Something wrong happened');
end
  댓글 수: 2
Steven Lord
Steven Lord 2019년 10월 21일
Show us exactly how you call this function. What are you passing into it as input?
Yu Liu
Yu Liu 2019년 10월 22일
Hello Steven, the function reads a text file and displays it on the command window. The input is the name of an existing file.

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

답변 (1개)

Daniel M
Daniel M 2019년 10월 20일
편집: Daniel M 2019년 10월 20일
try
% some code here
x = 1:5;
for n = 0:4
y = x(n); % can't access x at position zero!
end
catch ex
% some code to handle it
errorlog = n;
rethrow(ex) % throw the error to view message
end
  댓글 수: 2
Yu Liu
Yu Liu 2019년 10월 21일
Hi Daniel, Thanks for your answer! I tried the codes and it returned 'Subscript indices must either be real positive integers or logicals'. I still have no idea which part goes wrong. Do you have any idea about it?
Daniel M
Daniel M 2019년 10월 21일
If you run the above code in a script the error it throws should be:
Array indices must be positive integers or logical values.
Error in untitled27 (line 5)
y = x(n); % can't access x at position zero!
This tells you exactly what part goes wrong and where.

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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by