Overwrite lines

BlitzPlus Forums/BlitzPlus Programming/Overwrite lines

_PJ_(Posted 2016) [#1]
I'm expecting the answer, really to be 'That's a really bad way to do it' but here goes:

Basically I am writing my own ".ini" file read/write functions - However, I figured that it shouldn't be necessary to keep the entire list of possible settings, defaults and changes in memory, but that only those values changed need to be written back in the file.

Also, to save from copying all the other lines, whilst the file is OPEN, I ought to be able to just read and (overwrite) where necessary...

At first, I fthought using Read/WriteLine might be more convenient than Bytes etc. since ini files are written in lines, right? :D

However, there's some weird things happening with FilePos() that I am having trouble resolving.
I imagine, it's due to some lines being different lengths, but I think I need some help to sort it out.

The actual code is nested so deep in other stuff, but the principle is exemplified like this:

Global FILEPATH$=GetEnv("TMP")+"\"+"Test.txt"

Local oldPos=0
Local s$

Local FILE=OpenFile(FILEPATH)

While (Not(Eof(FILE)))
	oldPos=FilePos(FILE)
	s=Lower(Trim(ReadLine(FILE)))
	If (Left(s,4))="data"
		SeekFile(FILE,oldPos)
		WriteLine FILE,"Data YES"
	End If
Wend
CloseFile FILE


I should add of course, that I used a 'test' file consisting of:

A line
Another Line
Some Line
Data 1
Whatever
Data ?
Some random line

and placed in the location specified by the %TMP% environment variable.


Simply the two lines that begin with "Data" should be the only ones affected. In the REAL code, the specifics for line selection are a little more complex, but that complexity isn't relevant-


Dan(Posted 2016) [#2]
From the Manual:

SeekFile (filehandle, offset)

Note, extreme care needs to be exercised when updating files that contain strings since these are not fixed in length.

Which means, writing a data of the type string shall be calculated very carefully.

here is a quick test program to demonstrate it:



and the output of it, (the test.txt)

[test]
ad=2
=2
c=32


the output when seekfile (file,8):

[test]
d=2
b=2
c=32


and the output as above, but now writing c=21 to it:

[test]
c=21
=2
c=32


so in order for this to work,(as you have described it), your code has to make sure, that the length of the new line is the same as the old line.


_PJ_(Posted 2016) [#3]
Ah, the good old manual!
I really must learn to look there more :)

Thanks, Dan, That's exactly what's happening!