[Gambas-user] Rewrite a line of a File
Eilert
eilert-sprachen at ...221...
Fri May 7 12:08:53 CEST 2004
Hi,
I've done such things several things for various programs.
Dimitri Bellini schrieb:
> Dear Gianni
> I have think the same solution as you say in the last mail. No other solution
> is possible? :-)
>>read all of it, split into lines for an array, and then search and replace
>>for the correct line, then save the file again with array contents. Or read
This is the fastest solution but implies that the config-file is written
by the machine and never by the user.
>>config file line by line, and save every line in another file during
>>reading, with the modification of the correct line.
That is the more elegant way allowing for the user to tweak the file if
necessary and even allowing for comments and stuff.
My solution as a prototype for ini-style files. This is not real code
and maybe not all Gambas correct:
open one file for output(#2), the other for input(#1)
while not eof(1)
line input #1, t$ 'read one line
po=instr(t$, "=")
if po = 0 then 'not a real config line
print #2, t$ 'just copy the line
else 'a real config line
'line is split up into left and right part:
l$=ucase$(trim$(left$(t$,po-1)))
r$=ltrim$(mid$(t$,po+1))
'now search if you recognize the option you look for:
if l$="MY_OPTION" then 'yes, make up a new line for it:
t$="my_option = " & myvalue$
print #2, t$
else 'no, another one, just copy:
print #2, t$
end if
end if
wend
close the two files, delete the original one and rename the new one to
the old name.
Of course you can refine the thing. For instance it's unnecessary to
look for further lines once you've found and changed the value you
wanted. Just copy the rest, that's somewhat faster.
And I did not consider the case when you did not find the desired option
- that should be added to the above example by all means. And if you
make "chapters" in the file to distinguish between several subjects -
that's another story. I once made a handful of helper functions in VB to
handle such a more complicated file - it's a shame, but I think it's
lost :-(
Regards
Rolf
More information about the User
mailing list