Ask Your Question
3

Using Python, how can we tally the number of lines of C source code with a preprocessed file as the input?

asked 2023-01-08 11:00:00 +0000

devzero gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2021-10-12 19:00:00 +0000

lalupa gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-01-08 11:00:00 +0000

Seen: 14 times

Last updated: Oct 12 '21