error using fprintf invalid file identifier use fopen

3 views (last 30 days)
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

Answers (2)

Stephen23
Stephen23 on 3 Nov 2015
Edited: Stephen23 on 3 Nov 2015
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 Comment
Image Analyst
Image Analyst on 3 Nov 2015
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

Sign in to comment.


Star Strider
Star Strider on 3 Nov 2015
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.

Categories

Find more on Programming Utilities in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!