how can ı solve this error ? Error using fprintf Invalid file identifier. Use fopen to generate a valid file identifier.

 Accepted Answer

Check the success of fopen in every case, under all circumstances, ever, nerver omit this test:
filename = 'myfile.txt';
filepath = cd;
file = fullfile(filepath, filename);
fid = fopen(file, 'wt');
if fid==-1
error('Cannot open file for writing: %s', file);
end
I guess you do not have privileges to write to the current folder.

4 Comments

In particular if you are using Windows and you clicked on the icon to start matlab and you have not changed directory since you started then you will be in a directory that you do not have write permission.
Even better is to get the very informative message returned by fopen:
[fid,msg] = fopen(file, 'wt');
assert(fid>=3,msg)

Sign in to comment.

More Answers (2)

Categories

Asked:

on 31 May 2015

Answered:

on 2 Oct 2018

Community Treasure Hunt

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

Start Hunting!