Comment count // and / * * / in C

4

I'm trying to do a program in C that opens a file .txt , .c or any other in read mode, to count the comments made with // or /* */ .

I'm doing the following way:

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

//funcao de contagem de comentarios
void contalinha(FILE *pFile,int *coment1L, int *comentVL)
{
    char buff_linha[100];
    char atual, prox;
    int i;

    while (!feof(pFile))
    { //DO
         fgets(buff_linha, 100, pFile);
            puts(buff_linha);//PROVA QUE O BUFF ESTA FUNCIONANDO
         for(i=0; i<= 100; i++)//laco lendo o buff da linha
         {
             atual = buff_linha[i];
             prox = buff_linha[i+1];

             if(atual == '/' && prox == '/'){
                  *coment1L += 1;// comentarios de uma linha
             }
             else
                if(atual == '/' && prox == '*'){
                 *comentVL += 1;// comentarios de varias linhas
                }
        }

       }
    return;
}

 int main (int argc, char *argv[])
 {
    int n = 0;
    int coment1L = 0, comentVL = 0, flag = 0, flag2 = 0;
    FILE *pFile;

    system("cls");

    pFile = fopen (argv[1], "r");

    if (pFile !=NULL)
    {
        printf("Lendo arquivo...\n\n");
        contalinha(pFile,&coment1L, &comentVL);
        fclose(pFile);

        if(strcmp(argv[2], "-c") || strcmp(argv[2], "-comment")){
                printf("\n\t\t - Contagem de Comentarios - \n\n");
                printf("\n\tnumero de comentarios: %d", coment1L + comentVL);
                printf("\n\tNumero de comentarios com //: %d", coment1L);
                printf("\n\tNumero de comentarios com /*: %d", comentVL);
                printf("\n\n");
        }

    }
system("pause");
return 0;
}

I will use it to read .c codes. I'm reading line by line from file, storing the line in a buff[100] vector and traversing that vector in search of // or /* . Even the part of storing in buff is working, but it seems to me that it is not traversing the vector looking for matches.

    
asked by anonymous 29.11.2015 / 18:47

1 answer

2

Hello.

I recommend that you change fgets to fscanf;

int line_size = fscanf( pFile, "%s", &buff_linha);
for(int i = 0 ; i < line_size ; i++ )
{
   // realiza a contagem
}

Another approach would be to call strlen

int line_size = strlen(buff_linha);

You're probably reading garbage when reading the whole vector and not just reading the string up to the character '\ 0'.

Think of a short line with 3 words giving 30 letters, what will your software count to the 100 character?!

    
30.11.2015 / 18:06