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

fprintfstrings

fn=sprintf('ridging_daily_evolution_1980.txt'); A=load(fn);
[m,n]=size(A);
for i=1:m-1
DUR=A(i,5);
if DUR ~=1
DATE=A(i-(DUR-1),1);
else
DATE=A(i,1);
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 lon 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);
This is the whole program, i don't know what's wrong with the code please help me out.
thanks in advance.

Best Answer

It seems that gn includes a folder path + file name. If the folder path does not exist, then fopen will fail. To fix, make the directory first before making the file. Also, add some assert or error or warning messages after fopen and mkdir to help you debug your code.
FolderPath = fullfile('events', DUR_NAME);
if ~exist(FolderPath, 'dir')
[Success, ErrMsg] = mkdir(FolderPath);
assert(Success > 0, 'ERROR making folder "%s" \n %s', FolderPath, ErrMsg);
end
gn = fullfile(FolderPath, STR_DATE); %fullfile is designed to make proper file name
[fid2, ErrMsg2] = fopen(gn,'wt');
assert(fid2 > 0, 'ERROR making file "%s" \n %s', gn, ErrMsg2);
fprintf(fid2,'%10.2f %10.2f %10.2f %10.2f\n',B');
Related Question