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.




' FB 1.05.0 Win64
 
Sub removeLines(fileName As String, startLine As UInteger, numLines As UInteger)
  If startLine = 0 Then 
    Print "Starting line must be more than zero"
    Return
  End If
  If numLines = 0 Then
    Print "No lines to remove"
    Return
  End If 
  Dim fileNum As Integer = FreeFile
  Open fileName For Input As #fileNum
  If err > 0 Then
    Print "File could not be opened"
    Return
  End If
  Dim tempFileName As String = "temp_" + fileName
  Dim fileNum2 As Integer = FreeFile
  Open tempFileName For Output As #fileNum2
  Dim count As Integer = 0
  Dim ln As String
  Dim endLine As UInteger = startLine + numLines - 1 
  While Not Eof(fileNum)
    Input #fileNum, ln
    count += 1
    If count >= startLine AndAlso count <= endLine Then Continue While
    Print #fileNum2, ln
  Wend
 
  If count < startLine Then
    Print "No lines were removed as starting line was beyond end of file"
    Print
  ElseIf count < endLine Then
    Print "Only "; count - startLine + 1; " line(s) were removed as not enough lines to remove more"
    Print
  Else 
    Print Str(numLines); " line(s) were removed"
    Print
  End If
  Close #fileNum : Close #fileNum2
  Kill(fileName)
  Name (tempFileName, fileName)
End Sub
 
removeLines("foobar.txt", 2, 2)
removeLines("foobar.txt", 5, 2)
removeLines("foobar.txt", 3, 4)
Print
Print "Press any key to quit"
Sleep