Blockland Forums > Modification Help

How do I search for a string in a fileobject/text file and get its line number?

Pages: (1/1)

Axolotl:

Example:

I want to find 4 in this list:

1
2
3
test
4
5

and then get its line number (5)

Headcrab Zombie:

Untested

--- Code: ---%file = new FileObject();
%file.openForRead("file.txt");
while(!%file.isEoF())
{
%line = %file.readLine();
if(%line $= "4")
break;
%linesRead++;
}
%file.close();
%file.delete();

--- End code ---
Then check the value of %linesRead

Axolotl:

thanks, did I make it into function form properly:


--- Code: ---function searchInTextFile(%file,%string)
{
%file = new FileObject();
%file.openForRead(%path);
while(!%file.isEoF())
{
%line = %file.readLine();
if(%line $= %string)
{
%file.close();
%file.delete();
return %linesRead;
}
%linesRead++;
}
%file.close();
%file.delete();
}

--- End code ---

EDIT: I redid the syntax

jes00:


--- Quote from: Axolotl on December 28, 2011, 02:11:43 PM ---thanks, did I make it into function form properly:


--- Code: ---function searchInTextFile(%file,%string)
{
%file = new FileObject();
%file.openForRead(%path);
while(!%file.isEoF())
{
%line = %file.readLine();
if(%line $= %string)
{
%file.close();
%file.delete();
return %linesRead;
}
%linesRead++;
}
%file.close();
%file.delete();
}

--- End code ---

EDIT: I redid the syntax

--- End quote ---
You must either define %path or put the path.

Axolotl:


--- Quote from: jes00 on December 28, 2011, 02:53:09 PM ---You must either define %path or put the path.

--- End quote ---
oops forgot to set %file to %path lol

Pages: (1/1)

Go to full version