Hi,
I've been trying to create a loop that will read an arbitrary text file under certain circumstances, but send an error for further prompt if it is not the correct file name (and/or extension).
However, I have the loop running perfectly if the file is there and correctly inputted by the user, if not then it still runs the next bit of the loop (the thank you message) and I get this error:
Error using textread (line 165)
File not found.
Error in Assignment (line 13)
EEGData = textread(Datafile);
My script is:
Datafile=input('Please enter filename with extension: ','s');
if exist ('eegdata.txt', 'file');
disp(sprintf('Thank you, please wait a moment'));
EEGData = textread(Datafile);
else
disp(sprintf('I''m sorry, this file does not exist, try again'))
end
Thanks!

 채택된 답변

Stephen23
Stephen23 2018년 3월 11일

0 개 추천

if 2==exist(Datafile, 'file')

댓글 수: 6

If I run this
Datafile=input('Please enter filename with extension: ','s');
if 2==exist(Datafile, 'file')
disp(sprintf('Thank you, please wait a moment'));
EEGData = textread(Datafile);
else
disp(sprintf('I''m sorry, this file does not exist, try again'));
end
then it sends the displayed error message and runs the rest of the script even if the file isn't correctly identified.
Jan
Jan 2018년 3월 11일
There is no need for an sprintf() here. But disp() is not useful also. Call error() instead.
Stephen23
Stephen23 2018년 3월 11일
편집: Stephen23 2018년 3월 11일
As Jan Simon wrote, you will probably find error more useful:
if 2 == exist(Datafile, 'file')
disp('Thank you, please wait a moment');
EEGData = textread(Datafile);
else
error('I''m sorry, this file does not exist, try again')
end
Or simplify the whole thing by removing the if entirely and calling assert:
assert(2==exist(Datafile,'file'),'This file does not exist, try again')
disp('Thank you, please wait a moment');
EEGData = textread(Datafile);
Zara Roddis
Zara Roddis 2018년 3월 12일
Ah that works brilliantly, thank you both
Zara Roddis
Zara Roddis 2018년 3월 13일
Is there a way of incorporating this into a loop so the script doesn't have to be reloaded each time the user inputs the wrong file?
Stephen23
Stephen23 2018년 3월 13일
편집: Stephen23 2018년 3월 13일
Try something like this:
isf = false;
msg = 'enter filename with extension: ';
while ~isf
fnm = input(msg,'s');
isf = 2==exist(fnm,'file');
msg = 'try another filename: ';
end
disp('Thank you, please wait a moment');
EEGData = textread(fnm);
Personally I find throwing an error a better choice.

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Adding custom doc에 대해 자세히 알아보기

질문:

2018년 3월 11일

편집:

2018년 3월 13일

Community Treasure Hunt

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

Start Hunting!

Translated by