I want to count the lines of a c file ignoring the lines that have comments or empty lines , i came up with the following code but my string ( char pointer) only returns three chars instead of the whole line:
FILE* pf = NULL;
char *chaine;
int count=0;
int com=0;
pf=fopen("test.c","r+");
while(!feof(pf))
{
if(com%2==0)
count++;
fgets(&chaine, sizeof(chaine),pf);
if(&chaine=='\n' || &chaine==' ' || strstr(&chaine, "//") != NULL)
{
count--;
}
if(strstr(&chaine, "//*") != NULL || strstr(&chaine, "*//") != NULL)
{
com++;
}
printf("The line %d have the following string : %s\n",count,&chaine);
}
//printf("The number of lines est : %d", count);
Solved
Thanks for the answers especially for @Michael Walz i found that i have problems with my pointers. After i re-adjusted my if conditions now the line counter works just fine and this is the working code:
#include <stdio.h>
#include <string.h>
int main(void)
{
FILE* pf = NULL;
char chaine[1000];
int count = 0;
int com = 0;
pf = fopen("test.c", "r");
while (1)
{
if (com % 2 == 0 | strstr(chaine, ";//") != NULL)
count++;
if (fgets(chaine, sizeof(chaine), pf) == NULL)
break;
if (chaine[0] == '\n' || chaine[0] == "" || strstr(chaine, "//") != NULL)
{
count--;
}
if (strstr(chaine, "/*") != NULL)
{
com++;
}
if (strstr(chaine, "*/") != NULL)
{
com++;
}
}
fclose(pf);
printf("The file have %d line code", count);
}