why fopen can't generate a valid file identifier (when create new file with permission of 'writing')

8 views (last 30 days)
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!

Accepted Answer

Stephen23
Stephen23 on 23 Jun 2018
Edited: Stephen23 on 23 Jun 2018
[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 Comments
Stephen23
Stephen23 on 23 Jun 2018
Edited: Stephen23 on 23 Jun 2018
"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.

Sign in to comment.

More Answers (1)

bokkie
bokkie on 23 Jun 2018
oh, I create a folder for this new empty file, and it works now. Thanks anyway, I learned something new, the 'assert' command!

Categories

Find more on Variables in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!