I am writing a python program which reads C++ program files from a folder. The program then strips only certain parts from the C++ code read and writes them into a new separate file.
This is the C++ code that I am trying to strip:
#include <stdio.h>
int max(int num1, int num2);
//selectmethod
int main () {
int a = 100;
int b = 200;
int ret;
ret = max(a, b);
printf( "Max value is : %d\n", ret );
return 0;
}
int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
The only parts I am interesting in taking are marked with a
//selectmethod
comment. In the example code above, this would be the main()
method.
Right now I have a python code which reads this file and writes all of the file contents into an output file. However, I want to modify my code so the output file will only contain this:
int main () {
int a = 100;
int b = 200;
int ret;
ret = max(a, b);
printf( "Max value is : %d\n", ret );
return 0;
}
The python code I have so far is below:
import glob
import os.path
list_of_files = glob.glob('/my/input/files/*.cc')
def main():
for file_name in list_of_files:
print(file_name)
f= open(file_name, 'r')
lst = [];
plist = [];
for line in f:
fline = line.strip()
lst.append(fline)
plist.append(line)
f.close()
print(lst)
f=open(os.path.join('/my/output/files/path',
os.path.basename(file_name)), 'w')
for line2 in plist:
f.write(line2)
f.close()
if __name__ == "__main__":
main()
How can I modify my code to only extract the method below lines starting with //selectmethod
?