Advertisement
Nahid8195

Comment Removal in C

Dec 8th, 2022
678
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.69 KB | None | 0 0
  1.  
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <stdbool.h>
  5.  
  6. int main()
  7. {
  8.     char *program = 0, *modified_program = 0;
  9.     int file_length = 0, i = 0, j = 0;
  10.     bool s_cmt = false;
  11.     bool m_cmt = false;
  12.  
  13.  
  14.     FILE *fp = fopen("input.c", "r");
  15.     FILE *fp2 = fopen("output.c", "w");
  16.  
  17.     if (!fp)
  18.     {
  19.         printf("Source can't be opened");
  20.         exit(-1);
  21.     }
  22.  
  23.     fseek(fp, 0, SEEK_END);
  24.     file_length = ftell(fp);
  25.     fseek(fp, 0, SEEK_SET);
  26.  
  27.     program = (char *)malloc(file_length + 1);
  28.     modified_program = (char *)malloc(file_length + 1);
  29.     fread(program, sizeof(char), file_length, fp);
  30.     program[file_length] = '\0';
  31.  
  32.     printf("Before removing comment:\n");
  33.     for (i = 0; i < file_length; i++)
  34.     {
  35.         printf("%c", program[i]);
  36.     }
  37.  
  38.     for (int i = 0; i < file_length; i++)
  39.     {
  40.         if (program[i] == '/' && program[i + 1] == '/')
  41.         {
  42.             s_cmt = true;
  43.             i++;
  44.         }
  45.  
  46.         else if (program[i] == '/' && program[i + 1] == '*')
  47.         {
  48.             m_cmt = true;
  49.             i++;
  50.         }
  51.  
  52.         else if (s_cmt == true && program[i] == '\n')
  53.         {
  54.             s_cmt = false;
  55.         }
  56.         else if (m_cmt == true && program[i] == '*' && program[i + 1] == '/')
  57.         {
  58.             m_cmt = false;
  59.             i++;
  60.         }
  61.         else if (s_cmt || m_cmt)
  62.             continue;
  63.         else
  64.         {
  65.             modified_program[j] = program[i];
  66.             j++;
  67.         }
  68.     }
  69.     modified_program[j] = '\0';
  70.  
  71.     fputs(modified_program, fp2);
  72.     printf("\n\n\n\nAfter removing comment:\n");
  73.     fputs(modified_program, stdout);
  74.  
  75.     fclose(fp);
  76.  
  77.     return 0;
  78. }
  79.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement