Borrar filtros
Borrar filtros

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

8 visualizaciones (últimos 30 días)
Dani
Dani el 8 de Oct. de 2023
Comentada: Walter Roberson el 8 de Oct. de 2023
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 comentarios
Dyuman Joshi
Dyuman Joshi el 8 de Oct. de 2023
What are the values of outputtextfile and f1?
Dani
Dani el 8 de Oct. de 2023
my workspace says the value of f1 is -1 and the value of outputtextfile is a 1x1 table containing my directory, i think

Iniciar sesión para comentar.

Respuestas (2)

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

Iniciar sesión para comentar.

Categorías

Más información sobre Tables en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by