如何使用Racket语言在纯文本文件的特定行写入字符串?

问题描述 投票:0回答:1

我是 Racket 语言的新手,我不知道如何在纯文本文件的特定行写入字符串(新行)。

我已经看到 append 程序执行在文件末尾插入新行的工作。

此外,Racket 文档还讨论了计算位置、线和列,但是我没有找到易于理解的示例(至少对我来说)。

一个例子可以更好地说明我想要的。

假设一个文件(称为

test.txt
)有 10 行,我必须在第 7 行和第 8 行之间写一个字符串
" New information starts here."

我的意思是在成功插入新行后,

test.txt
文件将有11行。

file io racket
1个回答
2
投票

最简单的是复制旧文件并在复制时插入新行。然后删除旧文件并将新文件重命名为旧文件名。

复制可以如下进行:

#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))))))
© www.soinside.com 2019 - 2024. All rights reserved.