I am reading the C file using .readlines() to get all the individual lines of a C code file as elements of a list. If any of the list elements (i.e. C code line) a part of a multiline comment it needs to be replaced by ''(i.e. delete it but it will occupy the corresponding index of the list) so that indexing of further lines is not altered. Please check my code for details.
import re
#open and read sample.c so that code lines of sample.c are the element of list 'flist'
with open('sample.c',mode='r') as myfile:
flist = myfile.readlines()
pattern1 = re.compile(r'\/{2}.*') # to match //
pattern2 = re.compile('\/\*.*\*\/') # to match /*......*/ in a single line or element of flist
pattern3 = re.compile('\/\*') # to match /*
pattern4 = re.compile('\*\/') # to match */
# to delete comments present in a single code line or can say in an individual element of 'flist', it's working fine.
for index,line in enumerate(flist):
if pattern2.search(line):
flist[index] = pattern2.sub("",line)
if pattern1.search(line):
flist[index] = pattern1.sub("",line)
# to delete comment starting in one line and ending in the subsequent line, **this following part is not working**
cmnt_e = True
cmnt_s = False
for index,line in enumerate(flist):
if pattern3.search(line) and cmnt_e == True:
cmnt_s = True
cmnt_e = False
if pattern3.search(line) and cmnt_s == True:
cmnt_e = True
cmnt_s = False
if cmnt_s == True and cmnt_e == False:
flist[index] = ''