Author Topic: Deleting a Line in a File  (Read 586 times)

How would you delete a line in a file? As an example, I have an ID list for something and I want to make a servercmd to delete a certain line, like /deleteid 1337 would delete a line in the file that says 1337, how would I do this?

Re-write the entire file while omitting the line you want to "delete".

Re-write the entire file while omitting the line you want to "delete".
XD
Win. You get one of my few cookies.
 :cookie:
anyway, ctrl f?

XD
Win. You get one of my few cookies.
 :cookie:
anyway, ctrl f?
You're an idiot, he wasn't joking. That's how you'd do it.

Didn't Wizzeh give you that code block that did this?

This is the code i used to delete a certain line.
Code: [Select]
function deleteline(%File,%lineNum)
{
if(!isFile(%File))
{
echo("Could not find file, " @ %file @ ".");
}
else
{
%Fo = new fileobject();
%Fo.OpenForRead(%File);
%i = 0;
while(!%Fo.isEOF())
{

%LN = %i;
%i++;
%Line = %Fo.Readline();
if(%LN != %LineNum)
{
%LineChar[%LN] = %Line;
}
}
%Fo.close();
%Fo.OpenforWrite(%File);
%A = 0;
while(%A < %i)
{
%AN = %A;
if(%AN $= %LineNum)
{
%A++;
%Fo.WriteLine(%LineChar[%A]);
}
else
{
%Fo.WriteLine(%LineChar[%A]);
}
%A++;
}
%Fo.close();
%Fo.delete();
}
}

That's going to use a lot of memory having to load the entire file into arrays. I'd go with something like this:
Code: [Select]
function deleteLine(%file,%lineNumber)
{
   %fileIn = new FileObject();
   if(!%fileIn.openForRead(%file))
      return false;

   %fileOut = new FileObject();
   if(!%fileOut.openForWrite(%file))
      return false;

   while(!%fileIn.isEOF())
   {
      %i++;
      %line = %fileIn.readLine();
      if(%i $= %lineNumber)
         continue;

      %fileOut.writeLine(%line);
   }
   %fileIn.delete();
   %fileOut.delete();

   return true;
}
This is possible because the openForRead method loads the entire file into memory so you can physically edit the same file simultaneously without affecting the return of the readLine method of the reading FileObject.
« Last Edit: December 10, 2009, 05:09:31 PM by Ephialtes »

That's cool. I wasn't aware that openForRead stored the lines in the memory, I thought it just told windows it was reading the file or something.