MATLAB: Problem with textscan when file doesn’t exist.

text filetextscan

In my program I check if there is stored information on the user in userdata.txt. When the file doesn't exist yet I get the error:
??? Error using ==> textscan
Invalid file identifier. Use fopen to generate a valid file identifier.
At line:
data = textscan(fid,'%s%s%s');
Here is the relevant code:
if ~exist('userdata.txt','file')
new = fopen('userdata.txt','w');
fclose(new);
end
fid = fopen('userdata.txt','r');
data = textscan(fid,'%s%s%s');
fclose(fid);

Best Answer

Either insert a check if the file exists (use exist('userdata.txt','file')), or wrap this in a try-catch block. I would advise the first.