gpt4 book ai didi

c - 如何计算 .c 文件中的 ifs?

转载 作者:太空宇宙 更新时间:2023-11-04 00:03:26 26 4
gpt4 key购买 nike

我需要一些帮助来完成我的代码。该程序需要从一个 .c 文件中找到所有的 if 并计算它们。到目前为止,我能够找到所有后跟 '(' 的 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;
}

关于c - 如何计算 .c 文件中的 ifs?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33746515/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com