对于给定的 C 代码,我想打印每个函数的函数名称和行数。
下面是我的代码:
struct fundetails
{
int nooflines;
char funcname[SIZE];
}s[SIZE];
char *ffname(char *line,char *name)
{
int i=1,j=0;
char *dt;
strtok(line,"(");
dt = strchr(line,' ');
if(dt[i] == '*')
i++;
while(dt[i] != '\0')
{
name[j]=dt[i];
i++;
j++;
}
name[j] ='\0';
return NULL; //...
}
int main(int argc, char **argv)
{
if(argc < 2)
{
printf("Give the filename \n");
printf("Usage: %s filename\n", argv[0]);
return -1;
}
int i, lines =0, funlines =0,count =0, fn =0, flag =0, fg=0,size=0,emptyflag=0,commandflag=0;
char c[SIZE],b[SIZE],st[SIZE],d[SIZE];
char *fname;
int command[]={};
FILE *fd;
fd = fopen(argv[1],"r");
while(fgets(c,SIZE,fd))
{
emptyflag=0;
lines++;
for(i=0;i<(sizeof(command)/4);i++)
{
if(lines == command[i])
{
commandflag=1;
break;
}
}
strcpy(st,c);
strtok(st," ");
size = strlen(c);
if(size == 1 && (strcmp(c,"\n"))== 0)// Checking for empty line
emptyflag=1;
if( !strcmp(st,"struct")) // Checking whether line is structure or struct function
fg=1;
for(i=0;i<size;i++)
{
if(commandflag)
{
break;
}
while( c[i] =='\t' || c[i] == ' ')
{
i++;
}
if( c[i] == '{')
{
count++;
if(flag)
{
if(!emptyflag)
funlines++;
else
emptyflag=0;
}
if(count ==1 && fg ==1)
{
if(b[strlen(b)-2] == ')')
{
fn++;
printf("Dhahira");
printf("Function %d is Started..............\n", fn);
flag = 1;
printf("Dhahira");
ffname(b,fname);
printf("Function name is:%s\n",fname);
}
else
{
count--;
}
}
else if(count == 1)
{
fn++;
printf("Function %d is Started..............\n", fn);
flag = 1;
ffname(b,fname);//...
printf("Function name is:%s\n",fname);
}
break;
}
else if( c[i] == '}')
{
count--;
if(count ==0 && fg ==1)
{
flag = 0;
printf("No of lines in the function %d is: %d\n", fn, funlines);
printf("Function %d is finished..........\n", fn);
s[fn-1].nooflines=funlines;//...
strcpy(s[fn-1].funcname,fname);//..
funlines = 0;
fg=0;
}
else if(count ==0)
{
flag = 0;
printf("No of lines in the function %d is: %d\n", fn, funlines);
printf("Function %d is finished..........\n", fn);
s[fn-1].nooflines=funlines;//...
strcpy(s[fn-1].funcname,fname);//..
funlines = 0;
}
else if(count == -1)
{
count=0;
fg=0;
}
else
{
if(!emptyflag)
funlines++;
else
emptyflag=0;
}
break;
}
else if(flag ==1 && fg==1)
{
if(!emptyflag)
funlines++;
else
emptyflag=0;
break;
}
else if(flag)
{
if(!emptyflag)
funlines++;
else
emptyflag=0;
break;
}
break;
}
if(commandflag == 1)
commandflag = 0;
else
strcpy(b,c);
}
printf("FUN_NAME\tNO_OF_LINES\n");
for(i=0;i<fn;i++)
{
printf("%s\t\t%d\n",s[i].funcname,s[i].nooflines);
}
return 0;
}
我得到以下输出。
Function 1 is Started..............
Segmentation fault (core dumped)
我认为该ffname
功能可能是一个原因。但是,当我在该行上方包含一个 printf 语句时printf("Function %d is Started..............\n", fn);
,它仍然不打印该行。所以,我无法弄清楚这个问题背后的真正原因。请指导我解决这个问题。