I have downloaded the latest version of the Linux kernel and I want to perform thorough analysis on it. I want to start by eliminating comments from all the source and header files that belong to it. I am using a code I wrote sometime ago and I want to use it recursively. In the past I tested it on my code and it worked fine, but since I want to use it on a wide scale, I want to know if the code is consistent and successful in all cases.
Can you help me determine if it has bugs that do not deal with removing comments and create mess in certain cases?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int RemoveComments(const char *filename, const char *Output);
int main(void)
{
RemoveComments("file.cpp", "output.cpp");
return 0;
}
int RemoveComments(const char *filename, const char *Output)
{
#define NOT_COMMENT (!DOUBLESLASH_Comment && !ASTERISK_SLASH_Comment)
clock_t t1 = clock();
FILE *input, *output;
if (fopen_s(&input, filename, "r"))
{
perror(filename);
exit(1);
}
if (fopen_s(&output, Output, "w"))
{
perror(Output);
exit(1);
}
int c, d;
bool DOUBLESLASH_Comment = 0, ASTERISK_SLASH_Comment = 0, flag = 0;
int s_QUOTED = 0, d_QUOTED = 0;
while ((c = getc(input)) != EOF)
{
switch (c)
{
case '\\':
{
if (NOT_COMMENT)
{
if (flag == 1)
flag = 0;
else
flag = 1;
}
}break;
case '\'':
{
if (NOT_COMMENT && !d_QUOTED)
{
if (!flag)
{
s_QUOTED++;
}
}
}break;
case '"':
{
if (NOT_COMMENT && !flag)
{
if (!s_QUOTED)
{
d_QUOTED++;
}
}
}break;
case '/':
{
if (NOT_COMMENT && !d_QUOTED)
{
if ((d = getc(input)) == '*')
{
ASTERISK_SLASH_Comment = 1;
}
else if (d == '/')
{
DOUBLESLASH_Comment = 1;
}
else
{
if (d != EOF)
{
ungetc(d, input);
}
}
}
}break;
case '*':
{
if (ASTERISK_SLASH_Comment)
{
if ((d = getc(input)) == '/')
{
if ((c = getc(input)) == EOF)
return 0;
ASTERISK_SLASH_Comment = 0;
}
else
{
if (d != EOF)
{
ungetc(d, input);
}
}
}
}break;
case '\n':
{
if (DOUBLESLASH_Comment)
{
DOUBLESLASH_Comment = 0;
}
}break;
}
if (NOT_COMMENT && c != '\\') flag = 0;
if (d_QUOTED == 2) d_QUOTED = 0;
if (s_QUOTED == 2) s_QUOTED = 0;
if (NOT_COMMENT)
{
putc(c, output);
}
}
fclose(input);
fclose(output);
clock_t t2 = clock();
double elapsed = (double)(t2 - t1) / CLOCKS_PER_SEC;
printf("time elapsed : %.4f\n", elapsed);
return 0;
}