1

my task is to remove all the comments from a .c file and save the content in another .o file.

Given file:

// Sums two integers.
// Parameters: a, the first integer; b the second integer.
// Returns: the sum.
int add(int a, int b) 
{
    return a + b; // An inline comment.
}

Should look like:

int add(int a, int b) 
{
    return a + b; 
}

I have been trying this multiple times and I reached this state:

#include <stdio.h>

    int main(int argc, char **argv)
    {
        FILE * fPtr;
        fPtr = fopen("test.o", "w");

        char line[300];
        FILE *file = fopen("math_functions.c", "r");
        if (file == NULL) {
            printf("Error: Could not open %s!\n", "math_functions.c");
            return -1;
        }
        else {
            while(fgets(line, 300, file)) {
                int len = strlen(line);
                char helperLineArray[300];

                for (int i = 1; i < len; i++) {
                    if (line[i] == '/' && line[i-1] == '/') {
                        break;
                    }
                    else 
                    {
                        helperLineArray[i-1] = line[i-1];
                    }
                }
                fputs(helperLineArray, fPtr);
            }
        }

        return 0;
    }

Thank you in advance!

  • I would advise against initializing variables inside loops, for a start ;) - move things like "char helperLineArray[300];" outside of loops and conditional statements. – JWDN Feb 16 '19 at 16:30
  • As a side note, this seems possible directly with gcc, see for example this answer https://stackoverflow.com/a/2394040/6225525 – Olf Feb 16 '19 at 17:45

1 Answers1

0

I think, this would help

FILE * fPtr;
fPtr = fopen("test.o", "w");

char line[256],helperLineArray[10000];
FILE *file = fopen("math_functions.c", "r");
int j=0;
while (fgets(line, sizeof(line), file)){
    int len = strlen(line);
    for (int i = 0; i < len-1; i++) {
        if (line[i] == '/' && line[i+1] == '/') {
            break;
        }
        else
        {
            helperLineArray[j++] = line[i];
        }
    }
    helperLineArray[j++] = '\n';

  }
    fputs(helperLineArray, fPtr);
return 0;
tomal hossain
  • 86
  • 1
  • 9