"Error using textscan Invalid file identifier. Use fopen to generate a valid file identifier." - why am i getting this error?
2 views (last 30 days)
Show older comments
function allHurricaneData = getAllHurricaneData(allHurricanesFileName)
%UNTITLED2 Summary of this function goes here
% Detailed explanation goes here
FID = fopen(['data/' allHurricanesFileName]);
allNames = textscan(FID,'%s');
for i = 1:length(allNames{1})
hurricaneName = ['data/' allNames{1}{i}];
openFile = fopen(hurricaneName)
headerLine = fgetl(openFile);
properties = textscan(openFile,'%s %s %f %f %f %f %d %d' ,'Delimiter',',');
nameVariable =split(allNames{1}{i},'.');
allHurricaneData(i).name = nameVariable{1};
allHurricaneData(i).date = properties{1};
allHurricaneData(i).Xs = properties{5};
allHurricaneData(i).Ys = properties{6};
allHurricaneData(i).wind = properties{7};
allHurricaneData(i).pressure = properties{8};
end
end
0 Comments
Answers (2)
Voss
on 12 Nov 2022
Edited: Voss
on 12 Nov 2022
Most likely you get that error because the file ['data/' allHurricanesFileName] does not exist.
To find out for sure, you can take a look at the second output from fopen, which is an error message in case fopen cannot open the file:
[FID,msg] = fopen(['data/' allHurricanesFileName]);
if FID < 0
error('Cannot open the file: %s',msg);
end
allNames = textscan(FID,'%s');
0 Comments
Image Analyst
on 12 Nov 2022
Edited: Image Analyst
on 12 Nov 2022
Replace this
for i = 1:length(allNames{1})
hurricaneName = ['data/' allNames{1}{i}];
openFile = fopen(hurricaneName)
with this more robust code that has error checking in it:
for i = 1:length(allNames{1})
hurricaneName = ['data/' allNames{1}{i}];
if ~isfile(hurricaneName)
% File not found. Perhaps the folder name was not prepended with fullfile().
warningMessage = sprintf('Warning: this file does not exist:\n%s', hurricaneName)
uiwait(warndlg(warningMessage))
continue; % Skip to bottom of loop and keep going.
end
openFile = fopen(hurricaneName)
if openFile == -1
% Could be due to a variety of things, like it's open and locked in
% another application.
warningMessage = sprintf('Warning: error opening this file :\n%s', hurricaneName)
uiwait(warndlg(warningMessage))
continue; % Skip to bottom of loop and keep going.
end
% If you get here, it worked.
fprintf('Just opened :\n%s\n', hurricaneName)
0 Comments
See Also
Categories
Find more on Text Files in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!