Search code examples
clinescounting

counting the blank lines in a C program


I have to count the blank spaces in a program's code/file's text/console text. This is what I've tried so far:

void number_of_lines(int *brr, FILE *file)
{
    char string[60];
    int br = 0;
    //FILE *fileptr=fopen("test.txt","r");
    while (fgets(string, 60, file) != NULL)
    {
        if (string[0] == '\n')
        {
            br++;
        }
    }
    *brr = br;
}

The code should search for the blank lines by searching for the symbol for new line "\n" and it adds 1 to "brr" counter.

However when I delete all the words in a line, this line goes blank, but the function doesn't count it, because I haven't pressed enter(the new line "\n"), so it doesn't count it as a blank line.

So how would I count it now? Should I include if it finds the backspace symbol to add 1 to the counter or what?

(The name of the file and so on are written in another function, so I need to know only how to count the blank lines in a code,or the "if" criteria, if you have other suggestions, tell me )

Thank you :)


Solution

  • Check if (string[0] == '\0') or strcmp(string, "") == 0. If you don't press enter and the line is empty then the value of the string will be '\0' which indicates the end of a string.