Problem with textscan when file doesn't exist.
古いコメントを表示
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?
Adam Hicks
2017 年 12 月 14 日
編集済み: Adam Hicks
2017 年 12 月 14 日
採用された回答
その他の回答 (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).
カテゴリ
ヘルプ センター および 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!