I have an existing config file and l would like to insert/write a new line at line 64. I dont want to overwrite anything just add a new line.
Cant find out how to do it.รค in nim. Could someone pls point me in the right direction?
Thanks
In std/io (doc here https://nim-lang.org/docs/io.html#FileMode ) you can open a file using mode fmReadWriteExisting or fmAppend.
With the proc readLine (https://nim-lang.org/docs/io.html#readLine%2CFile) you can read until you are at the wanted position and of course you can write a buffer, cstring, char etc. in your file.
i would do something like this (the exact implementation depends on how big the file is, could it fit in memory etc..,):
import os
var inp = open(getAppDir() / "aaa.txt", fmRead) # open the original file
var outp = open(getAppDir() / "bbb.txt", fmWrite) # open an temporary output file
var lineNum = 0
for line in inp.lines():
lineNum.inc
outp.writeLine(line) # write the original line
if lineNum == 3: ## if you want to add stuff after line 3
outp.writeLine("the stuff you want to add")
inp.close()
outp.close()
# no you have two files
# then to something like this:
removeFile(getAppDir() / "aaa.txt")
moveFile(getAppDir() / "bbb.txt", getAppDir() / "aaa.txt")
aaa.txt is:
aaa
bbb
after me add stuff please
ccc
ddd
after the code runs:
aaa
bbb
after me add stuff please
the stuff you want to add
ccc
ddd