do you have a very clear idea of exactly what logic triggers a new file?
It looks as simple as
read line of original file. use this as file name (or first 2, or first N, ?? rows with #s??)
read original file and write to new file until find line that triggers a break.
on break, close new file and make new file name and repeat until original file empty.
do you need to protect yourself from 2 files same name due to the data?
Each new file should start with two # until it reaches the next two #. I mean for each new file I should have two lines starting with #. For the example above, the name of new files should be a_b and g_h.
Provide more details about your setup.
It's going to be a long thread if we have to keep making guesses as to what you're seeing on screen and typing at your keyboard.
For example, what actual compiler are you using.
1 2 3 4 5
$ g++ --version
g++-5.real (Ubuntu 5.4.0-6ubuntu1~16.04.11) 5.4.0 20160609
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
$ g++ --version
g++ (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
Copyright (C) 2011 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.