error using fprintf invalid file identifier use fopen

I am using fopen and fprintf to read data from array and export to a text file. It works fine when I started running the GUI for several times. However, fprintf started to give error message later on, while the exported file is incomplete too.
error message: Error using fprintf Invalid file identifier. Use fopen to generate a valid file identifier.
May I know what is wrong in the coding:
fid=fopen(fileexportpath,'w'); %Export
fprintf(fid,'%s %s\r\n','Headline: ',Title); %headline
fprintf(fid,'\r\n'); %spacing
for i = 1:TotalFile %total file imported
for j = 1:Length_Individual_File % length of each file
fid=fopen(fileexportpath,'a'); %append and write
fprintf(fid,'%3.3f ',colA(j,i));
fprintf(fid,'%2.5f\r\n',colB(j,i));
end
fprintf(fid,'\r\n'); % leave a space
fclose('all');
end

답변 (2개)

Stephen23
Stephen23 2015년 11월 3일
편집: Stephen23 2015년 11월 3일
Your code opens the same file multiple times in a loop, without closing it. Once that file is open there is no need to keep opening it again (unless you want to change its read/write mode, in which case you should fclose it first).
Because your code only refers to one file fileexportpath you only need to fopen it once, and fclose it once:
fid = fopen(fileexportpath,'wt');
fprintf(fid,...)
for m = 1:M
for n = 1:N
fprintf(fid,...)
end
end
fclose(fid);
Note that you should fclose using the fid value (rather than using 'all'), as otherwise your code will close any other open files. This is not robust programming if you intend to write useful functions. For this reason you need to pay careful attention to which files you have opened and keep close track of them.
Note that you should avoid using i and j as the loop variable names, as these are both names of the inbuilt imaginary unit.

댓글 수: 1

You'd better check if you want a "friendly" error message rather than have it barf up a bunch of cryptic red error text:
fid = fopen(fileexportpath,'wt');
if fid ~= -1
fprintf(fid,...)
for m = 1:M
for n = 1:N
fprintf(fid,...)
end
end
fclose(fid);
else
message = sprintf('Error opening %s for writing', fileexportpath);
uiwait(warndlg(message));
end

댓글을 달려면 로그인하십시오.

Star Strider
Star Strider 2015년 11월 3일
If you are creating a new file, see if changing your initial fopen call to:
fid=fopen(fileexportpath,'a+'); %Export
and deleting this line in your loop:
fid=fopen(fileexportpath,'a'); %append and write
does what you want.

카테고리

도움말 센터File Exchange에서 Standard File Formats에 대해 자세히 알아보기

태그

질문:

PF
2015년 11월 3일

답변:

2015년 11월 3일

Community Treasure Hunt

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

Start Hunting!

Translated by