0

I want to insert some text to my c++ file after certain line ( pattern ). The following is my file structure.

38 #include "stdlib.h"
39 #include "string.h"
40 #include "malloc.h"
41 

  ...

324 void DMProcMon::threadManagerMonitorThread(DMProcMon* dmProcMon)
325 {

    ...

338 while (dmState == DVProcMon::Active &&
339         DmManService::getDCMRestartingFlag() == 0){
340     try{

342         setupTimerVerification(dmProcMon);
343         setupSignalVerification(dmProcMon);
344
    ....

360 }

I want to add code coverage macros using gcov. So basically what I need to achieve is

  1. Add below text after all the #include statements.

    45 #ifdef GCOV
    46 extern "C"
    47 void _gcov_flush();
    48 #endif
    
  2. Add the below text after the while statement in the threadManagerMonitorThread function

    #ifdef GCOV
    _gcov_flush();
    #endif
    

So final code will loos like as below.

38 #include "stdlib.h"
39 #include "string.h"
40 #include "malloc.h"
41 

45 #ifdef GCOV
46 _gcov_flush();
47 #endif

  ...


324 void DMProcMon::threadManagerMonitorThread(DMProcMon* dmProcMon)
325 {

    ...

338 while (dmState == DVProcMon::Active &&
339         DmManService::getDCMRestartingFlag() == 0){
340     try{

342 #ifdef GCOV
343 _gcov_flush();
344 #endif

346         setupTimerVerification(dmProcMon);
347         setupSignalVerification(dmProcMon);
348
    ....

360 }

What is the best way to do this. I would like to do this with either bash or pythyon.

Thanks ~S

janos
  • 120,954
  • 29
  • 226
  • 236
user2677279
  • 127
  • 3
  • 10
  • 1
    You may want to learn how to use `ed` see [its documentation](http://www.gnu.org/software/ed/manual/ed_manual.html) – Basile Starynkevitch Oct 17 '13 at 05:31
  • `Awk` should be the right tool, it addresses rows by regular expressions and provides a powerful language for text editing. – remigio Oct 17 '13 at 05:42
  • Your first `ifdef` section is not included in your final code. And second section is not after a `while`, it's after a `try`. In what way does it matter? – Birei Oct 17 '13 at 07:27

1 Answers1

0

You might use sed to insert a line after/before a line containing a certain pattern. See this: https://stackoverflow.com/a/11695086/2749648.

Also here is the explanation on how to insert a line after a block of code (this will help you with the #include block) but i am not sure on how to fix the while statement. If while statement is on a single line, it would be easy, but that is hard to guarantee.

Community
  • 1
  • 1
Claudiu
  • 1,469
  • 13
  • 21
  • Thanks for the answer. but in my case as this is a C++ file I want to insert the lines inside the particular function scope and inside the while statement and inside try statement. So it is not a very straight forward substitution or insertion. – user2677279 Oct 17 '13 at 07:42