任务和代码:读入一个C程序,判断其中是否只有一个main()函数,输出“暂时没有发现问题”,或者“没有main()函数”,或者“不能定义多个main()函数”;
/*
文件名:main.c
作者:小风景
完成日期:2016.7.12
问题描述: 读入一个C程序,判断其中是否只有一个main()函数,输出“暂时没有发现问题”,或者“没有main()函数”,或者“不能定义多个main()函数”;
程序输出:
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int checkmain();
int main()
{
int result = 0;
result = checkmain();
if(result == 0)
{
printf("没有main函数!\n");
}
else if(result == 1)
{
printf("暂时没有发现问题!\n");
}
else
{
printf("不能定义多个main函数!\n");
}
return 0;
}
int checkmain()
{
int result = 0;
char readinfo[1024] = {0}; //存放读取的字符串
char testinfo[10] = "main()";
FILE *fp = NULL;
if((fp = fopen("source.c","r")) == NULL) //以只读的方式打开文件
{
printf("open source.c file error!\n");
exit(1);
}
while(fgets(readinfo,sizeof(readinfo),fp)) //每次读取一行,读取失败返回null
{
if(strstr(readinfo,testinfo)) //利用已有的函数进行比较
{
result++;
}
}
fclose(fp);
return result;
}
程序运行结果:
总结:对于字符串的比较,上述程序只能确定最简单的包含main()字符串的程序,由于main函数中还能带有参数,程序中的字符串中可能也带有main()字段,如果需要一一判断,则需要更为复杂的程序。