フィルターのクリア

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 Center および File ExchangeTables についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by