Problem with textscan when file doesn't exist.
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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);
2 commentaires
Adam
le 14 Déc 2017
Why are you trying to read data from a file you have only just created which has nothing in it?
Réponse acceptée
Rik
le 14 Déc 2017
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.
5 commentaires
Rik
le 14 Déc 2017
I always try to provide an explicit path to avoid these things. You can get the path to the folder this script is in by using dbstack('-completenames'), or using one of many other options, including this FEX submission: find_containing_folder. With fileparts you can easily move up the folder tree if you need to.
Plus de réponses (1)
Guillaume
le 14 Déc 2017
It would be interesting to know under which circumstances your code generates the error. The code does not make much sense, but should not generate an error.
If the file does not exist, the code creates an empty one, which it'll then read. Of course, since the file is empty, so will be data.
Note that while testing for the existence of a file before opening works in most cases, it's not robust. There are plenty of reasons why a file might exist at the point where you test for its existence but not anymore when you actually open it, even if it's on the next line. Antivirus, OS background operations, network disk going down, some other process moving the file, etc. may make the file disappear.
A better way is to simply catch the failure and respond appropriately.
fid = fopen('userdata.txt', 'r');
try
data = textscan(fid, '%s%s%s');
fclose(fid);
catch
msg = ferror(fid);
if ~isempty(msg)
disp(['Failed to read or open file because: ' msg]);
end
end
which will cope with more problems than just the file not existing (e.g. you don't have read permission on the file).
0 commentaires
Voir également
Catégories
En savoir plus sur Large Files and Big Data dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!