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

8 visualizzazioni (ultimi 30 giorni)
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!

Risposta accettata

Stephen23
Stephen23 il 23 Giu 2018
Modificato: Stephen23 il 23 Giu 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 Commenti
Stephen23
Stephen23 il 23 Giu 2018
Modificato: Stephen23 il 23 Giu 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.

Accedi per commentare.

Più risposte (1)

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

Categorie

Scopri di più su Variables in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by