Error using fprintf Invalid file identifier. Use fopen to generate a valid file identifier.

12 views (last 30 days)
Hi everyone, am getting this error message and i don't know how to fix it.
B = [STR_DATE,num2str(lon),num2str(lat),STR_DUR];
gn=sprintf('events/%s/%s',DUR_NAME,STR_DATE);
fid2 = fopen(gn,'wt');
fprintf(fid2,'%10.2f %10.2f %10.2f %10.2f \r\n',B');
fclose(fid2);
this is how i used the fprintf function.
  7 Comments
Adam Danz
Adam Danz on 13 Jul 2018
Edited: Adam Danz on 13 Jul 2018
Something could be wrong, then, with your gn variable. Could you post the gn string?

Sign in to comment.

Answers (2)

Adam Danz
Adam Danz on 12 Jul 2018
If fopen cannot open the file, it returns -1. If the value of your 'fid2' is not -1, respond to this answer in the comment section and we can dig deeper.
Check that your file can be found, is not protected, and is accessible.

siya lolo
siya lolo on 13 Jul 2018
for i=1:m-1
if A(i,5)~=0 && A(i+1,5)==0
DUR=A(i,5);
if DUR ~=1
DATE=A(i-(DUR-1),1);
else
DATE=A(i,1);
end
end
STR_DUR=num2str(DUR);
STR_DATE = num2str(DATE);
if DUR < 10
DUR_NAME = sprintf('0%s',STR_DUR);
else
DUR_NAME = sprintf(STR_DUR);
end
lat=A(i,3);
lon=A(i,2);
B = [STR_DATE num2str(lon) num2str(lat) STR_DUR];
gn=sprintf('events/%s/%s',DUR_NAME,STR_DATE);
fid2 = fopen(gn,'wt');
fprintf(fid2,'%10.2f %10.2f %10.2f %10.2f\n',B');
end
fclose(fid2);
end

Community Treasure Hunt

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

Start Hunting!