1

While trying to execute below program it is successfully removing multi line comments but for single line comments it is just removing one '/'. As while calling the function ( single_comment ) value of c is changed but value of d is same '\'. Due to this complete code provides output with '/' in it. Please help solving this.

/*Program to remove all the comments from a c program */

#include<stdio.h>
#include<stdlib.h>

void check_comment(char);
void incomment();
void single_comment();

char c,d;
FILE *fp ,*fp1;


int main (int argc, char** argv)
{
    fp = fopen(argv[1],"r+");
    fp1 = fopen(argv[2],"w");


    if(fp == NULL)
    {
        perror("Error has occured");
        printf("Error occured.\n");
        exit(0);
    }

    fp1 = fopen(argv[2],"w");

    if(fp1 == NULL)
    {
        perror("Error has occured");
        printf("Error occured.\n");
        exit(0);
    }

    while((c = fgetc(fp)) != EOF)
    {
        check_comment(c);

    }

    fclose(fp);
    fclose(fp1);
}

void check_comment(char c)
{
    if (c == '/')
    {
        if((d = fgetc(fp)) == '*' )
        {
            incomment();
        }
        else if(d == '/')
        {
            single_comment();               
        }
        else
        {
            fputc(c,fp1);
            fputc(d,fp1);
        }
    }
    else
    {
        fputc(c,fp1);
        fputc(d,fp1);
    }
}

/* For removing multiline comments */

void incomment()
{
    c = fgetc(fp);
    d = fgetc(fp);

    while(c == '*' || c == '/')
    {
        c = d;
        d = fgetc(fp);
    }
}

//For removing single line comments`

void single_comment()
{
    char c,d;   
    while((c = fgetc(fp)) != EOF)
    {
        if (c == '\n')
            return;
    }
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
Santosh
  • 11
  • 2
  • 1
    `single_comment` declares local variable `c`, so it doesn't affect the global variable. – Barmar May 24 '18 at 03:53
  • 1
    `c` should also be declared as `int`, not `char`. Otherwise the comparison with `EOF` might never succeed. – Barmar May 24 '18 at 03:54
  • 2
    Note that removing C comments properly is quite a lot harder than this code allows. You have to worry about `puts("/* this is not a comment */");` and so on (strings and multi-character constants like `printf("%d\n", '/*');` — which is legitimate, but the value is implementation-defined). There are also backslash-newline sequences to worry about, in general; however, those are probably not relevant to your code. And be grateful it is C and not C++ you are dealing with — C++14 is a lot tougher with raw character strings and numeric constants like `0b0010'1010`. – Jonathan Leffler May 24 '18 at 05:23
  • Amongst other questions, see [Remove comments from C/C++ code](https://stackoverflow.com/q/2394017/15168) – Jonathan Leffler May 24 '18 at 05:31

0 Answers0