我正在尝试从文本文件中逐行读取信息。我已经拥有它,它读取一行,将其存储在变量中,然后转到下一行,存储在变量中等(所以第1行 - >第2行 - >第3行等)。
代码:
'some while loop here'
str=textscan(read_in, '%s', 1, 'delimiter', '\n');
str=str{:}{:};
[str1]=textscan(str, '%d %s %d %f %f %f %f %s %d %f');
'end loop'
我想保持这个工作,但我也希望能够从下一行获取信息(即如果我在第3行,我想要从第4行获取信息而不实际#34;移动"到文本文件的第4行。)
Ex:我会在' 1 a b c'变成一个变量(称之为 currLine ),' 2 d e f'到另一个变量( nextLine )。所以在一行之后,我从第1行和第2行获得信息。然后我想要 currLine 来阅读' 2 d e f'和 nextLine 阅读' 3 g h i'。
1 a b c
2 d e f
3 g h i
.......
我目前的问题是每当我尝试使用' nextLine'时,它会推进"指针"文本文件(缺少更好的单词)到第3行。所以在1次迭代后我会有
currLine = '1 a b c'
nextLine = '2 d e f'
第二次迭代:
currLine = '3 g h i'
nextLine = '......'
任何帮助将不胜感激!
答案 0 :(得分:1)
您可以使用ftell
和fseek
调整文件中的位置。 ftell
将告诉您文件中的当前位置,fseek
允许您移动到文件中的任意位置。您可以在读取当前行后存储当前位置,然后在阅读下一行后将fseek
返回到此位置。
% Read current line
textscan(fid, '%s', 1);
% Remember where we are in the file
pos = ftell(fid);
% Read the next line
textscan(fid, '%s', 1)
% Now go back to where we were
fseek(fid, pos)
但这可能会变得非常低效。更好的方法可能是拥有一个保存下一行的变量,并在循环的开头,将当前值赋给该变量。
this_line = '';
while true
% Read next line
next_line = textscan(fid, '%s', 1);
% Do stuff with the two
% Move onto the next line
this_line = next_line;
end