问题描述:编写一个程序,使它读入被include语句修饰的一个文件并且输出这个文件。
分析:这道题的思路很简单,首先,读入源文件,然后在源文件中查找#include,然后获取包含的文件名,然后fread到内存中,如此继续下去。
有个问题纠结了很久:当在查找过程中发现strcpy(include,”#include”);时也会出现”#include”字符,应该对它进行过滤。
//include zuhonglei
//
#include <stdio.h>
#include <string.h>
int main(int argc,char *argv[]){
if(argc<1)
return -1;
char *name = argv[0];
char fullName[20];
strcpy(fullName,name);
strcpy(fullName+strlen(name),".c");
printf("%s\n",fullName);
FILE *fp = fopen(fullName,"r+");
if(!fp)
return -1;
char context[4097];
char context2[4097];
context2[4096] = '\0';
context[4096] = '\0';
while(fread(context,sizeof(char),4096,fp)!=0){
printf("%s\n",context);
}
fclose(fp);
//check the name of include
int i,j,index;
char include[10];
strcpy(include,"#include");
index = 0;
int nameIndex = 0;
char fileName[40];
char *prefix = "/usr/include/";
strcpy(fileName,prefix);
int fileLen = strlen(fileName);
for(i = 0;i<4097;i++){
if(context[i]=='/'&&context[i+1]=='/')//delete the whole line //
{
for(j = i;context[j]!='\n';j++);
i = j;
continue;
}
if(include[index]!='\0'){
if(context[i]!=include[index]){
index = 0;
}
else
index++;
}
if(include[index]=='\0'){
int tmp = fileLen;
if(context[i+1]!=' '){
index=0;
continue;
}
while(1){
i++;
if(context[i]=='>'){
index = 0;
break;
}
if((context[i]>='a'&&context[i]<='z')||context[i]=='.')
fileName[tmp++] = context[i];
}
fileName[tmp] = '\0';//delete >
printf("read fileName:%s\n",fileName);
fp = fopen(fileName,"r+");
if(!fp)
return -1;
while(fread(context2,sizeof(char),4096,fp)!=0)
printf("%s\n",context2);
fclose(fp);
}
}
return 0;
}