【问题标题】:identify function signature识别函数签名
【发布时间】:2013-09-01 18:46:09
【问题描述】:

我正在用 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");
}

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

【问题讨论】:

  • 您必须正确解析 C。这不是微不足道的。也许看看 libclang?
  • @H2CO3 什么是 libclang
  • 什么是谷歌?查看“libclang”的第一个匹配项。
  • @LorenzoDonati 很抱歉提出愚蠢的问题,但我从未听说过 libclang 这个词。所以我google了一下,找到了一些教程。阅读它们。

标签: c file file-io


【解决方案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;
}

【讨论】:

    猜你喜欢
    • 2021-01-23
    • 2016-11-25
    • 2021-07-04
    • 1970-01-01
    • 2012-08-29
    • 2012-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多