0

I have successfully removed single and multi line comments from input.c file but there are empty lines being created in output.c file wherever the comments were in input.c file. How to remove them?

#include<stdio.h>
int main()
{
  FILE *f1,*f2;
  char c;
  int i=0;
  f1=fopen("input.c","r");
  f2=fopen("output.c","w");

  while((c=getc(f1))!=EOF)
   {
       if(c=='/')
         {
            if((c=getc(f1))=='*' )
              {
                  do
                    {
                    c=getc(f1);
                    }while(c!='*');

                  c=getc(f1);
                  if(c=='/')
                  c=getc(f1);
              }
            else
             {
                 if(c=='/')
                  {
                       do
                       {
                       c=getc(f1);
                       }while(c!=10);
                  }
             }
         }
     fseek(f2,1,i++);
     putc(c,f2);
   }
fclose(f1);
fclose(f2);
return 0;
}
4

1 回答 1

1
c=getc(f1);
if(c=='/')
c=getc(f1);

here do:

if (c=='\n')
  c=getc(f1); /* that will read next char from input, when last red char is '\n' */

The last line reads next character after ending '/'. You should put c in output file only if it's not '\n'.

Same here:

do
{
c=getc(f1);
}while(c!=10);

Here always do:

c=getc(f1);

to remove '\n' that is must be in c variable to stop loop executing.

This should look like this to actually work.

#include<stdio.h>
int main()
{
  FILE *f1,*f2;
  char c;
  f1=fopen("fahr.c","r");
  f2=fopen("output.c","w");

  while((c=getc(f1))!=EOF)
   {
       if(c=='/')
         {
            if((c=getc(f1))=='*' )
              {
                  do
                    {
                    c=getc(f1);
                    }while(c!='*');

                  c=getc(f1);
                  if(c=='/')
            c=getc(f1);
          if(c=='\n')
            c=getc(f1);
              }
            else
             {
                 if(c=='/')
                  {
                       do
                       {
                       c=getc(f1);
                       }while(c!=10);
               c=getc(f1);
                  }
             }
         }
     putc(c,f2);
   }
fclose(f1);
fclose(f2);
return 0;
}
于 2013-08-19T10:56:26.280 回答