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

fwrite

Hello,
This matlab code reads a .raw file with a sequence of images and does small crops of the original one. After cropping, it saves them also in different .raw files with the name indicated.
I've checked the other sections of the program and they work perfectly; I get the correct small crops, but it fails to save them as .raw files.
for k=1:Ny
for i=1:Nx
filename = ['COMPT-EP2-Z40-U0-125x125x261-29298-', num2str(i), num2str(k),'.raw'];
fid=fopen(filename,'w+');
for j=1: length(CROP{1,1}(1,1,:))
fwrite(fid,CROP{k,i}(:,:,j));
end
fclose(fid);
end
end
And I get the following error:
Error using fwrite Invalid file identifier. Use fopen to generate a valid file identifier.
The value I get for fid after running the code is -1. I'm pretty sure the code worked three weeks ago.
What could be the problem??
Thank you very much.

Best Answer

According to the fopen documentation this error occurs "If fopen cannot open the file, then fileID is -1."
Usually this happens because the path has not been specified, or the filename is not correct. On Windows it might be related to permissions for a particular folder or file. Symbolic links may also cause problems.
It could be that the folder does not exist although you try to create a file there. Note that fopen will not create a folder, you have to arrange that yourself.
A common mistake that beginners make is to forget to specify the path to a file, as they mistakenly believe that MATLAB will see every file in the universe and be able to open them, even without specifying any path.
There may be some illegal characters in the string, this can also cause problems.
You can use exist and dir to check the folder contents and permissions.
Related Question