Problem with textscan when file doesn't exist.
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
Adam
2017-12-14
Why are you trying to read data from a file you have only just created which has nothing in it?
采纳的回答
Rik
2017-12-14
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 个评论
Rik
2017-12-14
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.
更多回答(1 个)
Guillaume
2017-12-14
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Large Files and Big Data 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!