Clear Filters
Clear Filters

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

8 views (last 30 days)
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 Comments
Dani
Dani on 8 Oct 2023
my workspace says the value of f1 is -1 and the value of outputtextfile is a 1x1 table containing my directory, i think

Sign in to comment.

Answers (2)

Image Analyst
Image Analyst on 8 Oct 2023
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 on 8 Oct 2023
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 Comment
Walter Roberson
Walter Roberson on 8 Oct 2023
Please note that if the directory named by output_dir does not exist, that fopen() will not create it.

Sign in to comment.

Categories

Find more on Tables in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!