This is a C Program to Count No of Lines, Blank Lines, Comments in a given Program.
This C Program counts the no of lines, blank lines, comments in a given program.
1. First count the number of lines in a file.
2. Count the number of blank lines.
3. Use the while loop for step 1-2.
4. Use another while loop to count the number of comment lines in a file.
5. Use fseek function to alter the position in the file.
Here is source code of the C Program to count no of lines, blank lines, comments in a given program. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C Program to Count No of Lines, Blank Lines, Comments in a given Program
*/
#include <stdio.h>
void main(int argc, char* argv[])
{
int line_count = 0, n_o_c_l = 0, n_o_n_b_l = 0, n_o_b_l = 0, n_e_c = 0;
FILE *fp1;
char ch;
fp1 = fopen(argv[1], "r");
while ((ch = fgetc(fp1))! = EOF)
{
if (ch == '\n')
{
line_count++;
}
if (ch == '\n')
{
if ((ch = fgetc(fp1)) == '\n')
{
fseek(fp1, -1, 1);
n_o_b_l++;
}
}
if (ch == ';')
{
if ((ch = fgetc(fp1)) == '\n')
{
fseek(fp1, -1, 1);
n_e_c++;
}
}
}
fseek(fp1, 0, 0);
while ((ch = fgetc(fp1))! = EOF)
{
if (ch == '/')
{
if ((ch = fgetc(fp1)) == '/')
{
n_o_c_l++;
}
}
}
printf("Total no of lines: %d\n", line_count);
printf("Total no of comment line: %d\n", n_o_c_l);
printf("Total no of blank lines: %d\n", n_o_b_l);
printf("Total no of non blank lines: %d\n", line_count-n_o_b_l);
printf("Total no of lines end with semicolon: %d\n", n_e_c);
}
1. Open the file and point it to the file pointer fp1.
2. Initialize the variables line_count, n_o_c_l, n_o_n_b_l, n_o_b_l, n_e_c to zero.
3. Using while loop read the next line character and store it in the variable ch. Do this until EOF.
4. Inside the loop and using if,else statements count the number of lines in the file and store it in the variable line_count.
5. Count of number of blank lines and store it in the variable n_o_b_l.
6. Check if the variable ch is equal to ;. If it is, then increment the variable n_e_c.
7. Use another while loop to count the number of comment lines and store it the variable n_o_c_l.
8. For the number of non blank lines subtract line_count from n_o_b_l.
9. Print the variables and exit.
Total no of lines: 204 Total no of comment line: 19 Total no of blank lines: 11 Total no of non blank lines: 193 Total no of lines end with semicolon: 66
Sanfoundry Global Education & Learning Series – 1000 C Programs.
Here’s the list of Best Books in C Programming, Data-Structures and Algorithms
- Check C Books
- Apply for C Internship
- Check Computer Science Books
- Practice Computer Science MCQs
- Watch Advanced C Programming Videos