views:

275

answers:

1

I have a config file to which I nee to add a couple of lines at the top of the file. When I try to do it from the command line, it removes the new line characters from my file and gives me an unformatted file.

So, my question is: Can I add some lines to the top of an already existing file and it should retain its formatting and new lines remain as new lines?

I am adding new lines to an existing file from another file.

+1  A: 

In Windows, you could create a new file with the additional information and then copy it plus the original file to a new file. Assuming you have an existing file called config.txt and a new file called new.txt:

copy new.txt+config.txt newConfig.txt

Or, you could type the old file and append to new.txt:

type config.txt >> new.txt

I think the second option would work in Linux, using the cat command rather than type.

Either way you'll neeed to delete the old config file and rename the new one.

If you want to do it in code:

  • allocate a buffer that's large enough to hold the combined file (i.e. length of old file + length of new file)
  • Read the new file into memory at the beginning of the buffer
  • Read the old file into memory starting at the byte after where the new file ended
  • Save the buffer to disk
Jim Mischel