why fopen can't generate a valid file identifier (when create new file with permission of 'writing')
8 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponse acceptée
Stephen23
le 23 Juin 2018
Modifié(e) : Stephen23
le 23 Juin 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 commentaires
Stephen23
le 23 Juin 2018
Modifié(e) : Stephen23
le 23 Juin 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.
Plus de réponses (1)
Voir également
Catégories
En savoir plus sur Variables dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!