我需要一些帮助来完成我的代码。程序需要从.c文件中查找所有ifs并对其进行计数。到目前为止,我能够找到所有字符串后面跟着'('(因为ifs有'('在它们之后)但是现在我' m担心可能会有一些以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;
}
答案 0 :(得分: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;
}