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

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

Your B is going to turn out as either a character vector or 2D character array if it works. That is unlikely to produce the results you want with the %f format.
What are the class() and size() of the variables you are putting together into B?
You are putting four variables together into B and you have four format items, as if you are expecting each variable to translate into a single column. But for gn to work properly, STR_DATE would pretty much need to be a character row vector, which would be unlikely to match the number of rows in lon and lat, and would be unlikely to be printed with a %f format.
I have a string variable,2floating numbers and also an integer and I want to print the variables in 4 different columns
If STR_DATE is a string() array, then when you use
sprintf('events/%s/%s',DUR_NAME,STR_DATE)
it is the same as if you had used
sprintf('events/%s/%s', DUR_NAME, char(strjoin(STR_DATE(:), ''))
so all of the entries in the string array get concatenated together to form the file name. Are you sure that is what is desired?
I guess that line is fine, what's giving me problems is the following: fid2 = fopen(gn,'wt'); fprintf(fid2,'%10.2f %10.2f %10.2f %10.2f \r\n',B'); i always get that error message.
The error "Invalid file identifier" is in reference to the fid2 variable if I'm not mistaken and that indicates the fopen() function didn't successfully access your file. Have you tested my response in the answer section below?
Something could be wrong, then, with your gn variable. Could you post the gn string?

Sign in to comment.

Answers (2)

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.
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

Asked:

on 12 Jul 2018

Answered:

on 13 Jul 2018

Community Treasure Hunt

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

Start Hunting!