why fopen can't generate a valid file identifier (when create new file with permission of 'writing')
9 ビュー (過去 30 日間)
古いコメントを表示
Hi all, I firstly generate a data file name 'outfilename', and next step, I will write something into this new empty file called 'outfilename' with the code below:
datafile = fopen(outfilename,'w');
fprintf(datafile,('sub_num\tsub_ini\tage\tgender\n'));
however, MATLAB returned:
Error using fprintf
Invalid file identifier. Use fopen to generate a valid file identifier.
I ran my codes step by step, the 'outfilename' was successfully created, but 'datafile' returned value of '-1', which means the 'fopen' code failed to create a new file called 'outfilename'.
I'm wondering why 'fopen' can't generate a valid file identifier. I use these codes before without such problem.
Many thanks if anyone could help!
0 件のコメント
採用された回答
Stephen23
2018 年 6 月 23 日
編集済み: Stephen23
2018 年 6 月 23 日
[fid,msg] = fopen(outfilename,'w');
assert(fid>=3,msg)
fprintf(fid,'sub_num\tsub_ini\tage\tgender\n');
fclose(fid);
If the file cannot be opened then the message will give more information why. I recommend that this assert statement is used every time fopen is used.
3 件のコメント
Stephen23
2018 年 6 月 23 日
編集済み: Stephen23
2018 年 6 月 23 日
"So 'fopen' is expected to create a new file, isn't it?"
If the path that you give fopen includes folders that do not exist then this will be an error, because fopen can create files, but it can't create folders. To create folders use the command mkdir.
その他の回答 (1 件)
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!