Post by B+ on Oct 16, 2018 15:27:44 GMT
How sweet, you can access a sequential file for adding or editing lines like a Random Access file. Sweet because the strings are variable length!
'Random access sequential files.txt for JB v2.0 B+ 2018-10-16
fName$ = "Test sequential file.dat"
[editAdd]
cls
call showFile fName$
print
input "(0 to quite) Enter a line number to edit > ";lNum
if lNum = 0 then print "Goodbye!" : end
line input "Enter the the line to edit or add > ";eaLine$
call editAddLine fName$, lNum, eaLine$
goto [editAdd]
end
sub editAddLine fileName$, lineNum, newLine$
if lineNum = 0 then exit sub 'no good
'avoid file exist erors
open fileName$ for append as #1
close #1
CRLF$ = chr$(13) + chr$(10) 'constant line ender
'inhale file
open fileName$ for input as #writeAtLine
f$ = input$(#writeAtLine, lof(#writeAtLine))
close #writeAtLine
'process: count and record positions of CRLF's in file contents
if right$(f$, 2) <> CRLF$ then f$ = f$ + CRLF$ 'balance line counts by CRLF$ count
pos = instr(f$, CRLF$) 'find end of first line
while pos 'find end positions of remaining lines until run out of CRLF's
if len(NLpos$) = 0 then NLpos$ = str$(pos) else NLpos$ = NLpos$ + " " + str$(pos) 'record crlf positions
count = count + 1 'count crlf's
pos = instr(f$, CRLF$, pos + 1) 'get next crlf if there is one
wend
'edit a line or add one or many?
if lineNum > count then 'add line(s) to lineNum spot
if lineNum = 1 then
txt$ = newLine$
else
txt$ = f$
while count < lineNum - 1
txt$ = txt$ + CRLF$
count = count + 1
wend
txt$ = txt$ + newLine$
end if
else 'edit the line
if lineNum = 1 then txt$ = "" else txt$ = mid$(f$, 1, val(word$(NLpos$, lineNum - 1)) + 1)
txt$ = txt$ + newLine$ + mid$(f$, val(word$(NLpos$, lineNum)))
end if
'remove last CRLF
if right$(txt$, 2) = CRLF$ then txt$ = left$(txt$, len(txt$) - 2)
'write to file in one go
open fileName$ for output as #writeAtLine
print #writeAtLine, txt$; '(;) prevents extra CRLF
close #writeAtLine
end sub
sub showFile filename$
'avoid file exist erors
open filename$ for append as #1
close #1
print filename$;":"
open filename$ for input as #1
while eof(#1) = 0
i = i + 1
line input #1, fline$
print right$(" ";str$(i);": ", 6);fline$
wend
close #1
end sub