필터 지우기
필터 지우기

Why do I keep getting an fopen error in my code? [absolute beginner]

조회 수: 8 (최근 30일)
Dani
Dani 2023년 10월 8일
댓글: Walter Roberson 2023년 10월 8일
My code is
filename = 'test02.txt';
outputtextfile = fullfile(output_dir, filename);
header = {'bad channels'};
f1 = fopen(outputtextfile,'w');
fprintf(f1,'%s\n',header{:});
fprintf(f1,'%d\n',removed_ch);
fclose(f1);
ERROR I get:
Error using fprintf
Invalid file identifier. Use fopen to generate a valid file identifier.
  댓글 수: 2
Dyuman Joshi
Dyuman Joshi 2023년 10월 8일
What are the values of outputtextfile and f1?
Dani
Dani 2023년 10월 8일
my workspace says the value of f1 is -1 and the value of outputtextfile is a 1x1 table containing my directory, i think

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

답변 (2개)

Image Analyst
Image Analyst 2023년 10월 8일
This works fine:
output_dir = pwd
removed_ch = 9999;
filename = 'test02.txt';
outputtextfile = fullfile(output_dir, filename);
header = {'bad channels'};
f1 = fopen(outputtextfile,'w');
fprintf(f1,'%s\n',header{:});
fprintf(f1,'%d\n',removed_ch);
fclose(f1);
What is f1? Is it -1? That means you can't write there, like it's a readonly folder or a non-existent folder or something like that. Use isfolder to check if the folder exists.

Walter Roberson
Walter Roberson 2023년 10월 8일
outputtextfile = fullfile(output_dir, filename);
If outputtextfile were a table, then certainly fopen() would fail. However in order for it to be a table in that code, then fullfile() would have to have returned a table.
If you are using the MATLAB-supplied fullfile() then:
Error using fullfile
All inputs must be strings, character vectors, or cell arrays of character vectors.
(Which is not completely true: fullfile() will also accept numeric inputs and will char() them)
and given any of those, fullfile() cannot return a table() object.
So if you are getting a table object for outputtextfile then it follows that at that point in the code, fullfile is one of:
  • a function handle pointing to something different than the MATLAB-supplied fullfile(); or
  • the name of a user-supplied or third-party supplied function that is not the same as supplied by MATLAB; or
  • is the name of a table() object that just happens to have a variable named 'test02.txt' and output_dir just happens to be a valid row number or row-name reference inside the table() object
... or possibly you are mistaken about outputtextfile being a table object at that point in the code.
  댓글 수: 1
Walter Roberson
Walter Roberson 2023년 10월 8일
Please note that if the directory named by output_dir does not exist, that fopen() will not create it.

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

카테고리

Help CenterFile Exchange에서 Tables에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by