[英]How to count ifs from .c file?
我需要一些帮助来完成我的代码。 该程序需要从.c文件中查找所有if,然后对其进行计数。 到目前为止,我能够找到所有后跟'('的字符串(因为ifs后跟'(')),但是现在我担心可能会有一些以if和后跟'( ”,它也会被计数(一个不同的函数或类似的东西)。所以我有一个想法来检查“ i”之前是否有东西,是否没有东西我会数一下,但是否有某种东西我的问题是我的主意是否好,如果主意好,如何做,如果主意不好,我该怎么办?
到目前为止,这是我的代码:
#include <stdio.h>
int main(){
FILE *file = fopen ("poohzad.c", "r");
char *ch = NULL;
int i=1;
if (file != NULL){
char line [256];
while (fgets(line, sizeof line, file) != NULL){
if (strstr(line, "if")){
ch=strstr(line, "if");
if(*(ch+2) == '(') printf("%s\n", line);
}
i++;
}
}
fclose (file);
return 0;
}
大部分错误检查都省略了。 需要您自担风险使用它。 (使用AStyle格式化,因此请不要对此发表评论)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int ifs;
/**
loads an ascii file, returns NULL on failure
*/
char *loadFile(char*fname){
char *buff;
int len;
FILE *fd;
fd=fopen( fname,"r");
if(!fd){
printf("error opening file '%s'\n");
exit(1);
}
fseek(fd,0,SEEK_END);
len=ftell(fd);
fseek(fd,0, SEEK_SET);
buff=malloc(len+1);
fread(buff,1,len,fd);
fclose(fd);
*(buff+len)=0;
return buff;
}
/**
placeholder what to do with the word
*/
void addWord(const char *word){
if(0)
printf("'%s'\n",word);
else
if(!strcmp(word,"if"))
ifs++;
}
/**
is operator simplified
*/
int isop(char c){
static char list[]=
"_"
"abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"0123456789";
return !strchr(list,c);
}
int main(){
char *pbuff,*buff,*ptr,c;
int pos;
pbuff=loadFile("main.c");
buff=pbuff;
ptr=pbuff;
while(c=*buff){
switch(c){
case '?':
if(0){
addWord("if");
}
ptr=&buff[1];
break;
case '#':
while(*buff && *buff!='\n'){
if(c=='\\') buff++;
buff++;
}
ptr=&buff[1];
break;
case '/': //comment?
//single line comment
if(buff[1]=='/'){
buff+=2;
while(*buff && *buff!='\n'){
if(*buff=='\\')buff++;
buff++;
}
//multi line comment
}else if(buff[1]=='*'){
buff+=2;
while(*buff && !((buff[-1]=='*') && (*buff=='/'))){
buff++;
}
}else{
//not a comment, just ignore it;
}
ptr=&buff[1];
break;
case '\"': //skip strings
case '\'':
buff++;
while(*buff && *buff!=c){
if(*buff=='\\') buff++;
buff++;
}
ptr=&buff[1];
break;
default:
if(isspace(c) || isop(c)){
if(ptr-buff){
*buff=0;
addWord((const char*)ptr);
*buff=c;
}
ptr=&buff[1];
}
}
buff++;
}
// take habit to free memory
free(pbuff);
printf("there are %d ifs in source file\n",ifs);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.