How to read a file?
by baylor wetzel · in Torque Game Builder · 05/29/2009 (6:23 pm) · 3 replies
What's the proper way to read all the lines from a file? i'm obviously making some kind of stupid mistake because it never reads the last two lines
It can parse this file:
i assume my loop check condition is wrong but i'm not sure how to fix it
function parseFile(%fileFQN)
{
%file = new FileObject();
if (!%file.openForRead(%fileFQN))
{
error("Can't read file " @ %fileFQN);
}
for (%line = %file.readLine();
!%file.isEOF();
%line = %file.readLine())
{
warn(%fileFQN @ ": " @ %line);
%key = getWord(%line, 0);
%value = getWord(%line, 2);
warn("key=[" @ %key @ "] value=[" @ %value @ "]");
}
%file.close();
}It can parse this file:
type = shirtbut not the same file without the last (3rd) line (oops, GG's forums automatically strip out the last two blank lines; lines 2 and 3 are just newlines). However, in this example
type = shirt image = x thumbnail = yit prints the first two lines and not the third
i assume my loop check condition is wrong but i'm not sure how to fix it
About the author
#2
So it goes: get next line, check if we reached the end of the file, do loop. When it reaches the last line of the file, it will grab the last line, then check if it had reached the end of the file, since you just grabbed the last line, it will be at the end of the file, and will quit out of the loop without processing the last line.
05/30/2009 (8:40 am)
This doesn't matter since you already solved it, but I wonder if the problem with the for loop was that it checks the continue condition after it gets the next line of the file on every iteration.So it goes: get next line, check if we reached the end of the file, do loop. When it reaches the last line of the file, it will grab the last line, then check if it had reached the end of the file, since you just grabbed the last line, it will be at the end of the file, and will quit out of the loop without processing the last line.
#3
03/19/2010 (1:54 pm)
Heya Baylor!!! Found you randomly while searching for something in the forums... Feel free to email me anytime!
Torque 3D Owner baylor wetzel
Not sure what's wrong with the for but it doesn't matter, the better way to do it is with a while statement
while(!%file.isEof()) { %line = %file.readLine(); warn(%fileFQN @ ": " @ %line); %key = getWord(%line, 0); %value = getWord(%line, 2); warn("key=[" @ %key @ "] value=[" @ %value @ "]"); }