Question

Is there a way to edit the contents of a single line of a text file in ColdFusion?

As I understand it, I would have to read and buffer the whole text file, then re-write it line by line as-is until I find the line I have to modify, put the value I want, then continue re-writing the rest of the lines as-is.

I don't like the idea of re-writing the whole file.. I want to find a way to edit a single line, what do you propose?

More details

Basically I have a config file that looks like this

my_own.thingy.blabla1 = "true";
my_own.thingy.bla_bla = 1337;
my_own.thingy.foo_bar_baz = "what ever...";

And my CFC controller receives a request like "edit bla_bla to 42"

I need to

  1. Read the config file into a variable
  2. Find the place in the variable where bla_bla is defined
  3. Replace the substring 1337 by 42
  4. Rewrite the file with the modified variable that contains the modified file text

I am looking for a good way to do steps 2 and 3 since #1 and #2 are trivial

EDIT : Somebody pointed me out to use JSON, but I have no clue how that would apply here.

Was it helpful?

Solution 2

Using JSON is a good way to go if you are not likely to want to edit the configuration file manually, but an 'old school' .INI style config file is easier to work with if you need to be able to jump in with a text editor.

I'd suggest creating a simple component with 4 methods: i) Read a config into a variable ii) Get the value of a config parameter iii) Update the value fo a config parameter iv) Write the whole config back to the file

As others have pointed out, you are going to end up updating the whole file anyway and unless the file is huge, your application performance impact is likely to be minimal.Keeping the code simple is likely to be a much greater benefit.

OTHER TIPS

Surely to edit a single line in a text file, when you come to "save" the file you have to rewrite the whole file anyway, however instead of writing it line by line why not read the whole file (using cffile read) into a variable, change the appropriate part of the file and then write the whole file back using cffile write.

Don't think I would recommend writing the file one line at a time to find the line you want to edit.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top