154k views
4 votes
Write a c program to count the total number of commented characters and words in a c file taking both types of c file comments (single line and block) into account.

User Pervin
by
5.9k points

2 Answers

1 vote

Answer:

The C program for characters will be like the one below:

Step-by-step explanation:

#include <stdio.h>

#include <stdlib.h>

int main()

{

FILE * file;

char path[100];

char ch;

int characters, words, lines;

/* Input path of files to merge to third file */

printf("Enter source file path: ");

scanf("%s", path);

/* Open source files in 'r' mode */

file = fopen(path, "r");

/* Check if file opened successfully */

if (file == NULL)

{

printf("\\Unable to open file.\\");

printf("Please check if file exists and you have read privilege.\\");

exit(EXIT_FAILURE);

}

/*

* Logic to count characters, words and lines.

*/

characters = words = lines = 0;

while ((ch = fgetc(file)) != EOF)

ch == '\0')

words++;

/* Increment words and lines for last word */

if (characters > 0)

{

words++;

lines++;

}

/* Print file statistics */

printf("\\");

printf("Total characters = %d\\", characters);

printf("Total words = %d\\", words);

printf("Total lines = %d\\", lines);

/* Close files to release resources */

fclose(file);

return 0;

}

User Roshan N
by
6.2k points
3 votes

#include<stdio.h>

#include<stdlib.h>

int comment1(FILE *fp)

{

char ch;

int count=0;

while(fscanf(fp,"%c",&ch)!=EOF)

{

if(ch=='\\')

{

return count;

}

count++;

}

return count;

}

int comment2(FILE *fp)

{

char ch;

int count=0;

while(fscanf(fp,"%c",&ch)!=EOF)

{

if(ch=='*')

{

fscanf(fp,"%c",&ch);

if(ch=='/')

{

return count;

}

count++;

}

count++;

}

return 0;

}

int main()

{

printf("Enter the file name:");

char s[1000],ch,ch1;

scanf("%s",s);

FILE*fp;

fp = fopen(s,"r");

int count=0;

while(fscanf(fp,"%c",&ch)!=EOF)

{

if(ch=='\"')

{

while(fscanf(fp,"%c",&ch)!=EOF)

{

if(ch=='\"')

{

break;

}

if(ch=='\\')

{

fscanf(fp,"%c",&ch);

}

}

}

else if(ch=='/')

{

fscanf(fp,"%c",&ch);

if(ch=='/')

{

count += comment1(fp);

}

else if(ch=='*')

{

count += comment2(fp);

}

}

}

printf("%d\\",count);

return 0;

}

User Denys Shabalin
by
5.3k points