Skip to content
Advertisement

Find known string in file then add string prior to it

I need to find a known string inside a config file and then add some content(another string) prior to this.

What is the most efficient way to do this?

Example:

JavaScript

filetomodify.config

JavaScript

Desired outcome:

JavaScript

I’ve been using fopen to access the file but this only allows to prepend or append content, by default with fwrite. I can’t currently think of an efficient way to meet my requirement.

Advertisement

Answer

This question essentially needs two answers:

  • One for the case, that the file is guaranteed to be small enough to be read into memory
  • One for the opposite case

The first version is easily achieved by

JavaScript

The second version needs more work, along the lines of

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement