1 | initial version |
Here is a Python script that can be used to tally the number of lines of C source code with a preprocessed file as the input:
import re
file_path = 'file.c' # replace with the file path of your preprocessed C file
with open(file_path, 'r') as f:
lines = f.readlines()
count = 0
for line in lines:
line = line.strip()
if line.startswith('#'):
continue
elif line.startswith('//'):
continue
elif line.startswith('/*'):
if '*/' not in line: # if comment extends to multiple lines
while '*/' not in line:
line = lines[count]
count += 1
line = line[line.index('*/')+2:]
else:
line = line[line.index('*/')+2:]
elif line == '':
continue
else:
count += 1
print('Total lines of C source code:', count)
This script reads in the contents of the preprocessed C file, strips each line of whitespace, and skips any lines that start with a preprocessor directive (#
), a single-line comment (//
), or a multi-line comment (/* ... */
). It then increments a line counter for each non-empty line that is not skipped. The final count is printed to the console.