Search code examples
fileioracket

How to write a string at a specific line of a plain text file using Racket language?


I am a newcomer in Racket language and I do not know how to write a string (a new line) at a specific line of a plain text file.

I have seen that the append procedure do the work inserting new lines at the end of the file.

Also, Racket documentation talks about Counting Positions, Lines, and Columns, however I found no easy understandable examples (at least to me).

An example may illustrate better what I want.

Suppose a file (called test.txt) has 10 lines and I have to write a string " New information starts here." between line 7 and 8.

I mean after the new line has been inserted successfully, the test.txt file is going to have 11 lines.


Solution

  • The simplest is to make a copy of the old file and insert the new line while copying. Then delete the old file and rename the new file to have the old file name.

    The copying could be done as follows:

    #lang racket
    
    ; insert-line : string number ->
    ;   Almost copies line for line the current input port to the current output port.
    ;   When line-number lines have been copied an extra line is inserted.
    (define (insert-line line line-number)
      (for ([l (in-lines)]
            [i (in-naturals)])
        (when (= i line-number)
          (displayln line))
        (displayln l)))
    
    ; insert-line-in-file : file file string number ->
    ;   copies file-in to file-out and inserts the line line at the given line number.
    (define (insert-line-in-file file-in file-out line line-number)
      (with-outout-to-file file-out
        (λ ()
          (with-input-from-file file-in
            (λ ()
              (insert-line line line-number))))))