1

我正在用 c 编写一个程序来识别函数的签名并复制到另一个文件中。

想法是确定任何行中的括号并将该行复制到文件中。之后我们可以检查返回类型和参数,以便区分构造 if, while 与除 main 之外的用户定义函数。

但是我的代码陷入了无限循环。找不到问题。

find_sig.c

#include <stdio.h>
int main()
{
int count=0;
char c;
FILE *f1,*f2;
f1=fopen("input.c","r");
f2=fopen("output.c","w");
while((c=getc(f1))!=EOF)
 {
    do
    {
        if(c=='(')
        {
            fseek(f1,-count,1);
            do{
                putc(c,f2);

            }while((c=getc(f1))!=')');
            count=0;
        }
        else
            count++;

    }while((c=getc(f1))!=10);
    count=0;
 }
fclose(f1);
fclose(f2);
return 0;
}

输入.c

#include<stdio.h>
void fun();
int main()
{
  fun();
  return 0;
}

void fun()
{
  printf("hello");
}

确定函数签名的任何其他想法都会非常有帮助。

4

1 回答 1

1

我想到了。

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

char str1[50];
int count=0,i=0;
int main()
{
char c;
FILE *f1,*f2;
f1=fopen("input.c","r");
f2=fopen("output.c","w");

while((c=getc(f1))!=EOF)
{
   if(c!=10)                                    //checks for /n
   {
       if(c=='(')
       {
           ++count;
           fseek(f1,-count,1);              //moves f1 to 'count' bytes back i.e. beginning of line
           i=0;
           while((c=getc(f1))!=';'&&c!='{') //checks for declaration or definition
           {
              str1[i++]=c;
           }

           if(strstr(str1,"main(")!=NULL)   //checks whether str1 contains main 
               return 0;
           else
               {
               fprintf(f2,"%s",str1);   // copies str1 in f2
               count=0;
               }
       }
       else
       count++;
   }

   else
       count=0;
   if(c==10)
         putc(c,f2);

}

fclose(f1);
fclose(f2);
return 0;
}
于 2013-09-02T18:05:53.257 回答