Header Ads Widget

Program to identify the comment in the code by using the file handling.

 Here we will use file handling . And first we will write the code in the file and then read the code from the file .

Code:-     First we should to create a file (.txt)

#include<stdio.h>
#include<string.h>
int main()
{
FILE *fp;
char str[200];
// logic for writing the code in the file
fp=fopen("file.txt","w");
if(fp==NULL)
printf("Error in opening the file\n");
else
{
char ch;
printf("Enter the $ for ending the editing\n");
scanf("%c",&ch);
fputc(ch,fp);
while(ch!='$')
{
scanf("%c",&ch);
fputc(ch,fp);
}
fclose(fp);
}
printf("The comments are:-\n");
// logic for finding the comment in the code
fp=fopen("file.txt","r");
if(fp==NULL)
printf("Error in opening the file\n");
else
{
while(fgets(str,200,fp)!=NULL)
{
int i,l,flag=0;
l= strlen(str);
for(i=0;i<l-1;i++)
{
// logic to find single line comment
if(str[i]=='/' && str[i+1]=='/')
{
for(int j=i+2;j<l;j++)
printf("%c",str[j]);
printf("\n");
break;
}
// logic to find comment is multiline
if(str[i]=='/' && str[i+1]=='*')
{
i=i+2;
for(int j=i;str[j];j++)
{
// if there is any single line comment inside
// the multiline
if(str[j]=='/' && str[j+1]=='/')
{
j+=2;
for(int k=j;k<l;k++)
printf("%c",str[k]);
break;
}
else
printf("%c",str[j]);
}
printf("\n");
flag=1;
break;
}
}
// if multiline comment found
// then scan next line for the full comment
if(flag==1)
{
while(fgets(str,200,fp)!=NULL)
{
int i=0;
l=strlen(str);
while(i<l-1)
{
// if there is any single line comment
if(str[i]=='/' && str[i+1]=='/')
{
i+=2;
for(int k=i;k<l;k++)
printf("%c",str[k]);
break;
}
else
{
if(str[i]=='*' && str[i+1]=='/')
{
flag=0;
break;
}
printf("%c",str[i]);
i++;
}
}
printf("\n");
// if comment end then break
if(flag==0)
break;
}
}
}
}
return 0;
}




Recommended Post:

Hackerearth Problems:-

Hackerrank Problems:-

Data structure:-

Key points:-

 MCQs:-

Post a Comment

0 Comments