我需要计算文件中函数的行数。 我有以下输入。
输入:
必需的输出:
示例:
int main()
{
line1;
line2;
line3;
}
int func()
{
line1
line2
line3
line4
line5
if(---) //line 6
{ //line 7
line 8
line 9
} //line10
}
所以如果我们将文件名和函数名称作为“func”
传递,上面的例子应该返回10请建议一些方法来做...
答案 0 :(得分:2)
代码具有严格的格式, INDENT 您的源文件
indent -kr -bap -nce -i8 -ts8 -sob -l80 -ss -bs -npsl -bl -bli0 file.c
awk + substr($ 0,1,1)匹配'{'和'}'
awk -F"," '{ if( index(v_func,$0)<10 ) { findfunc=1; } if( findfunc == 1) { if( substr($0,1,1) == "{" ) { lineCnt=0; } else if(substr($0,1,1) == "}" ) { print lineCnt; } else { lineCnt = lineCnt+1; } } }' v_func=$2 $1
答案 1 :(得分:0)
import sys,re
if len(sys.argv)<3:
print "Usage: %s filename functionname"%(sys.argv[0])
exit(0)
f=open(sys.argv[1],"r")
func=sys.argv[2]
linec=0
braces=1
lines=f.readlines()
for i in range(len(lines)):
if re.match(".{4}"+func,lines[i]):
break
lines=[s.strip() for s in lines]
lines=[s for s in lines if len(s)!=0]
for k in lines[i+2:]:
if k=="{":
braces+=1
if k=="}":
braces-=1
if braces<=0:
break
linec+=1
print linec
答案 2 :(得分:0)
建议去做..
非常粗略:
a) assume this is pedantic exercise for class, so ignore tricky bits like macros
b) open "filename"
c) read file into memory
d) strstr() for "function"
e) scan until you hit "{"
f) for(bracecount=1; bracecount > 0; )
g) ++ on {, -- }, skip char constants, skip comments, keep newline count
h) print newline count