The problem is to delete all comment lines from a C or C++ or any other programming languages that uses comment like single line comment ( // ) and multi-line comment (/**/).
The program given below will delete all the comment line in a file. If the code is not working properly please comment below in the comment section. If someone have some better approach also comment below.
#include <stdio.h>
#include <unistd.h>
#include <string.h>
void refine(const char line[])
{
char *sl = "//", *ml = "/*", *ptSingleLine, *ptMultiLine;
ptSingleLine = strstr(line, sl);
if ( ptSingleLine ) {
*ptSingleLine = '\0';
}
ptMultiLine = strstr(line, ml);
if ( ptMultiLine ) {
*ptMultiLine = '\0';
}
}
int findComment(const char *line)
{
char *singleLine = "//", *multiLine = "/*" ;
if ( strstr(line, singleLine) || strstr(line, multiLine)) {
return 1;
}
else {
return 0;
}
}
int main()
{
int found;
FILE *fin, *fout;
char ch, line[200], fname[100], temp[50];
printf("Enter The Name Of The File: ");
fflush(stdin);
gets(temp);
getcwd(fname, 99);
strcat(fname, "/");
strcat(fname, temp);
fin = fopen(fname, "r");
fout = fopen("new.c", "w");
if ( fin == NULL ) {
printf("\nFile %s Not Found.", fname);
}
else {
while ( fgets(line, 100, fin) != NULL )
{
found = findComment(line);
if( found == 1 ) {
refine(line);
fprintf(fout, "%s", line);
}
else {
fprintf(fout, "%s", line);
}
}
printf("\nDone Copying To 'new.c' W/O Comment Lines.");
fclose(fin);
fclose(fout);
}
return 0;
}