explanation for script containing while loop
1 次查看(过去 30 天)
显示 更早的评论
I was given a script for reading data from a specific file, and although the script works, I don't understand one section of it, it reads as follows:
fid = fopen(Folder);% open file to read
fseek(fid,0,-1);% set read position to beginning of file,
Linechk = strcmp(fgetl(fid),'*END*');% read in line 1
while Linechk == 0
Linechk = strcmp(fgetl(fid),'*END*');% go through lines until '*END*'
end
The main aim here is to find the line where the string END appears, following the appearance of END the data is stored. The question I have is that Linechk is equal to 0 initially (i.e. before the loop), then in following the loop it is equal to 1. I can't understand why it returns 1, surely the while loop only repeats when Linechk is equal to 0 therefore how does the condition remain true when it equals 1?
Entire code:
fid = fopen(Folder);% open file to read
fseek(fid,0,-1);% set read position to beginning of file,
% fseek(fileID, offset, origin).
Linechk = strcmp(fgetl(fid),'*END*');% read in line 1
while Linechk == 0
Linechk = strcmp(fgetl(fid),'*END*');% go through lines until '*END*'
end
n = 1;
while 1;
tline = fgetl(fid);% read in line
if ~ischar(tline), break, end;% if end of file, break and finish
data(n,:) = sscanf(tline,'%f');% put numbers in a matrix (in columns)
n = n+1;
end
fclose(fid);% close file
0 个评论
采纳的回答
Wayne King
2012-11-6
I'm not sure I understand your question. Presumably, the first fgetl() call does not obtain the string END, so the string compare is 0. Then the while loop continues the string comparison until the string is END at which time the value of Linechk goes to 1.
Once you exit the loop the value of Linechk is 1. Or perhaps better stated, Linechk equal to 1 keeps the while loop from being evaluated.
4 个评论
Walter Roberson
2012-11-6
In such a situation, the fgetl() after that would fetch line 10, the one after that would fetch line 11, and so on.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Multidimensional Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!