In: Computer Science
2. [50] 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.
`Hey,
Note: Brother if you have any queries related the answer please do comment. I would be very happy to resolve all your queries.
#include<stdio.h>
#include<stdlib.h>
int comment1(FILE *fp)
{
char ch;
int count=0;
while(fscanf(fp,"%c",&ch)!=EOF)
{
if(ch=='\n')
{
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 countWords(char s[])
{
int i,count=0;
for (i = 0;s[i] != '\0';i++)
{
if (s[i] == ' ' && s[i+1] != ' ')
count++;
}
return count;
}
int comment1s(FILE *fp)
{
char ch;
int count=0;
char s[10000];
int ct=0;
while(fscanf(fp,"%c",&ch)!=EOF)
{
if(ch=='\n')
{
s[ct]='\0';
return countWords(s);
}
s[ct++]=ch;
count++;
}
s[ct]='\0';
return countWords(s);
}
int comment2s(FILE *fp)
{
char ch;
int count=0;
char s[10000];
int ct=0;
while(fscanf(fp,"%c",&ch)!=EOF)
{
if(ch=='*')
{
fscanf(fp,"%c",&ch);
if(ch=='/')
{
s[ct]='\0';
return countWords(s);
}
s[ct++]='*';
}
s[ct++]=ch;
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("Characters: %d\n",count);
fclose(fp);
}
{
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 += comment1s(fp);
}
else if(ch=='*')
{
count += comment2s(fp);
}
}
}
printf("Words: %d\n",count);
fclose(fp);
}
return 0;
}
Kindly revert for any queries
Thanks.