Invalid file identifier. Use fopen to generate a valid file identifier.

124 vues (au cours des 30 derniers jours)
Hello,
I am trying to open a file, skip the first 6 lines (headers) and extract data from the rest of the lines in the file. Here is the code:
%%Declarations
targetinfo(1000)=struct('distance', 0, 'speed', 0, 'angle', 0, 'rcs', 0);
i=1; %index
count=0; %file size counter
[fid, message]=fopen('log.asc','r'); %open log file
%%Read file and extract relevant data
if fid==-1
disp('Error')
else
for k=1:6
header=fgetl(fid); %skip headers
end
while ~feof(fid)
line=fgetl(fid);
if line(16)=='S' || line(13)=='C' || line(1)=='T' %remove control and status signals
continue;
end
id=str2num(line(16:18));
line=line(41:63);
line=line(~isspace(line));
if id==100
canstatus=hex2dec(line(1:2));
targetcount=hex2dec(line(3:4));
canchannel=hex2dec(line(9:10));
else
targetinfo(i).distance=hex2dec(line(1:4));
targetinfo(i).speed=hex2dec(line(5:8));
targetinfo(i).angle=hex2dec(line(9:12));
targetinfo(i).rcs=hex2dec(line(13:16));
end
count=count+1; %increase file size counter
i=i+1; %increase index
fclose(fid); %close file
end
end
I am getting the error I have specified in the title. The value of fid returned is not -1 (it is 4 at the moment) and I do have access to the file, since I can open it in Notepad to view its contents.
I am not opening and closing the file multiple times, just once. Is there any reason I'm missing out?
Thank you for your help.

Réponse acceptée

Preethi
Preethi le 21 Nov 2016
hi,
you are closing the file in while loop and trying to access it again. use fclose() after you encountered feof
  2 commentaires
Pranav Thiagarajan
Pranav Thiagarajan le 21 Nov 2016
Thank you! That was stupid of me.
Oreoluwa
Oreoluwa le 29 Juil 2022
Had the same problem🤣

Connectez-vous pour commenter.

Plus de réponses (1)

daniel cheng yi lu
daniel cheng yi lu le 28 Nov 2018
For my situation, I have checked everything but missed an easy step.
Please select "Browse for folder" and browse for the folder which the current script is saved, before you run your 'fopen' code.
2018-11-28 (3)_LI.jpg
  5 commentaires
parivesh meena
parivesh meena le 27 Juin 2022
thanks budddy i got the same
Justin Bryant
Justin Bryant le 23 Fév 2023
Modifié(e) : Justin Bryant le 23 Fév 2023
Thanks helped me too!

Connectez-vous pour commenter.

Catégories

En savoir plus sur Low-Level File I/O 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!

Translated by