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

8 次查看(过去 30 天)
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 个)

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.

类别

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