How do I pass a filename to a routine in Matlab's command window?

7 ビュー (過去 30 日間)
Harald von der Osten
Harald von der Osten 2021 年 9 月 19 日
編集済み: Jan 2021 年 9 月 23 日
In the Matlab Command window I would like to run a function with an input parameter, like this:
>> xxxreplace oldGEOPLOT
s =
"./html/oldGEOPLOT.html"
Error using fread
Invalid file identifier. Use fopen to generate a valid file identifier.
Error in xxxreplace (line 14)
ff=fread(fid,'*char')';
I'm using this code :
function file=xxxreplace(x)
f=string(x);
s=strcat('./html/',f,'.html')
fid=fopen(s,'r');
ff=fread(fid,'*char')';
fclose(fid);
ff =strrep(ff,'.png" alt="">','.png" alt="" width="360">');
fid=fopen('./html/new.html','w');
fprintf(fid,'%s',ff);
fclose(fid);
disp(s)
end
Why do I get this error?
Thanks a lot,
Harry
  4 件のコメント
Matt J
Matt J 2021 年 9 月 19 日
Is the Current Folder the same in both cases?
Harald von der Osten
Harald von der Osten 2021 年 9 月 19 日
yes

サインインしてコメントする。

採用された回答

Jan
Jan 2021 年 9 月 19 日
編集済み: Jan 2021 年 9 月 23 日
The error message is clear: The file does not exist. Although you assume, that the current folder is the same, this is not true. Check this explicitly:
function file = xxxreplace(x) % What is "file"?
s = fullfile('./html/', [x, '.html']);
[fid, msg] = fopen(s, 'r');
assert(fid > 0, msg);
ff = fread(fid,'*char')';
fclose(fid);
ff = strrep(ff,'.png" alt="">','.png" alt="" width="360">');
[fid, msg] = fopen('./html/new.html', 'w');
assert(fid > 0, msg);
fprintf(fid, '%s', ff);
fclose(fid);
end
Trusting on the current folder is a bad programming practice. Any timer or gui callback might change the current folder unexpectedly. Prefer to use absolute file names.
  3 件のコメント
Harald von der Osten
Harald von der Osten 2021 年 9 月 19 日
thanks for your help. Hmmm...the file really exist:
Harald von der Osten
Harald von der Osten 2021 年 9 月 19 日
hey, now it works:
changing
s = fullfile('./html/', [f, '.html']);
to
s = fullfile('./html/', [x, '.html']);
made obviously the job. Thanks to all who helped me !!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeFile Operations についてさらに検索

タグ

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by