Task

Remove a specific line or a number of lines from a file.

This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed).

For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from the file foobar.txt, the parameters should be: foobar.txt, 1, 2

Empty lines are considered and should still be counted, and if the specified line is empty, it should still be removed.

An appropriate message should appear if an attempt is made to remove lines beyond the end of the file.




 
; Contents of file 'input.txt' before deletion of lines :
;
; cat
; dog
; giraffe
; lion
; mouse
; pig
; tiger
; zebra
 
EnableExplicit
 
#Output$ = "output.txt"; insert path to temporary output file 
 
Procedure RemoveLines(Input$, StartLine, NbLines)
  Protected lineCount = 0
  Protected endline = StartLine + NbLines - 1
  Protected row$
 
  If Not ReadFile(0, Input$)
    PrintN("Error opening input file")
    ProcedureReturn
  EndIf
 
  If Not CreateFile(1, #Output$)
    PrintN("Error creating output file")
    CloseFile(0)
    ProcedureReturn 
  EndIf
 
  While Not Eof(0)
    row$ = ReadString(0)
    lineCount + 1
    If lineCount < StartLine Or lineCount > endLine    
      WriteStringN(1, row$)
    EndIf    
  Wend
 
  If endLine > lineCount
    PrintN("Attempted to remove lines beyond the end of the file")
    ; but still allow removal of lines (if any) up to the end of the file
  EndIf
 
  CloseFile(0)
  CloseFile(1) 
 
  If Not DeleteFile(Input$)
    PrintN("Unable to delete input file so output file can be renamed")
    ProcedureReturn
  EndIf
 
  If Not RenameFile(#Output$, Input$)
    PrintN("Unable to rename output file")
  EndIf
 
EndProcedure
 
Define fInput$
 
If OpenConsole()
  ; delete lines 2,3 amnd 4 of 'input.txt'
  fInput$ = "input.txt"; insert path to input file 
  RemoveLines(fInput$, 2, 3)
  PrintN("")
  PrintN("Press any key to close the console")
  Repeat: Delay(10) : Until Inkey() <> ""
  CloseConsole()
EndIf
 