I need a program to count the lines of a .txt or .c file and return me the following things:
File:
Simple Comment: N lines
Multiline Comment: N lines
Total Lines: N lines
I have this:
if (pFile != NULL)
{
do {
c = fgetc(pFile);
if (c == '\n') n++;
} while (c != EOF);
And I don't know how to implement the rest of it.
I tried with the strstr() function as well, didn't get it neither.
So n == # of lines in the file.
You'll need another variable that counts every time you see the character / followed by another / (this is easy, same way that you're doing n++ basically, but it should look like
And then for multiline comments, you do the same thing, and just count /, just like above. You'll just have to keep an eye on when n gets incremented (every line), and when the other ones get incremented (Once for every line with // and once for every line that starts with / and until you hit a */).
You can write a state machine that should handle most cases.
As you scan the file, you'll be in one of the following states:
/
, which may be the start of a single- or multi-line comment. If the next character is a/
, you'll go into the SINGLE_COMMENT state. If the next character is a*
, you'll go into the MULTI_COMMENT state. For any other character, you go back into the TEXT state.//
token; you will stay in this state until you see a newline character; once you see the newline character you'll increment the number of single-line comments as well as total lines, and go back to the TEXT state./*
token; you will stay in this state until you see the next*/
token. Any newline you see in this state will cause the multi-comment line counter to be incremented along with the total lines.*
. If the next character is/
, you'll go back to the TEXT state. If the next character is*
, you'll stay in the SAW_STAR state. Otherwise you'll go back to the MULTI_COMMENT state.There are edge cases that I'm not dealing with (such as encountering an EOF while in a comment state), but the following should be a reasonable example of how you can do stuff like this.
Note that nested comments won't be counted; i.e., if a
//
-delimited comment appears within a/* */
-delimited comment, only the multi-comment counter will be updated.You will probably want to factor the counting logic into its own function; just trying to keep the example as straightforward as I can.
EDIT
Here's a table-driven equivalent to the program above. I create a
state
table to control state transitions and anaction
table to control what happens when I change state.Running the file on itself gives us
which I think is right. This has all the same weaknesses as the first version, just in a different form.