Saturday 30 January 2016

Remove comments from file

0

Remove comments from a file. Store the new file without comments. Here I am assuming the file-name which has comments that is the source file is present in c drive with name src.cpp. While the file with the resultant content is named as res.cpp and will be created in c drive. 
This question needs basic knowledge of file handling.
C language has two types of comments.

 

1. Single line comment: 

This type of  comment starts with double slash (//) and it ends with enter character.

// This is a comment

2. Multi-line comment: 

This type of comment is used to multiple lines. It uses pair of slash and star to start and end a block of comment. 

/* This
is multi-line
comment */

Here goes the code:


#include <stdio.h>
#define INM 1       /* Reading multi-line comment */
#define INS 2       /* Reading single-line comment */
#define OUT 0       /* Not in comment */

int main() {
   int mode, i, l, j, k;
   FILE *src, *res; // File pointers

   /* File handling stuff: fopen is used to open a file */
   src = fopen("C:\\src.cpp", "rt");
   /* rt defines that opened file in reading mode */
   res = fopen("C:\\res.cpp", "wt");
   /* wt defines that opened file is in writing mode */
   
   mode = OUT;
   for (i = 1;;i++){
     
      if ((l = getc(src)) == EOF) {
         printf("File ended");
         break;
      }
      /* In comment section */     
      if (mode == OUT && l == '/') {
         if ((j = getc(src)) == EOF) {
            printf("File ended");
         }
         else if (j == '*') {
            mode = INM;
            /* entering into multi-line comment */
         }
         else if(j == '/'){
             mode = INS;
             /* entering into single-line comment */
         }
      }
      /* code to be written into new file */
      else if (mode == OUT) {
         putc(l, res);
      }
 
      /* Leaving comment */
      if (mode == INM && l == '*') {
         if ((j = getc(src)) == '/') {
            mode = OUT;
            /*end of multi-line comment*/
         }
      }
      if( mode == INS && l == '\n'){
          mode = OUT;
          /*end of single line comment*/
      }
   }
   
   /*close the file pointers*/
   fclose(src);
   fclose(res);
   return 0;
}


Results:

Contents of src.cpp

Don't remove this
// Single line comment : Remove this
/* Multi-line comment:
Remove this*/
Don't remove this!!


Contents of res.cpp

Don't remove this

Don't remove this!!


Thanks for reading!!

0 comments:

Post a Comment