问题描述:
C提供形如
#include filename
的语句,它读入文件filename并将其插入到include语句处。include语句可以嵌套;换句话说,文件filename本身还可以包含include语句,但是显然一个文件在任何连接中都不能包括它自己。
编写一个程序,使它读入被include语句修饰的一个文件并输出这个文件.
实现如下:
#include
#include
#include
#define MAXLINE 1024
void process_line(const char *filename);
int main(int argc,char **argv)
{
process_line("string.h");
}
void process_line(const char *filename)
{
char *buf,*fName, *match, *subfile;
fName = (char *)malloc(sizeof(char)*MAXLINE);
buf = (char *)malloc(sizeof(char)*MAXLINE);
match = (char *)malloc(sizeof(char)*MAXLINE);
subfile = (char *)malloc(sizeof(char)*MAXLINE);
memset(fName,'\0',MAXLINE);
memset(buf,'\0',MAXLINE);
memset(match,'\0',MAXLINE);
memset(subfile,'\0',MAXLINE);
strcpy(match, "#include");
strcpy(fName, "/usr/include/");
strcat(fName, filename);
FILE *fp;
while((fp = fopen(fName, "r+"))==NULL)
{
printf("open %s error:%s\n",fName, strerror(errno));
memset(fName,'\0',MAXLINE);
strcpy(fName, "/usr/include/linux/");
strcat(fName, filename);
sleep(2);
}
while(fgets(buf, MAXLINE, fp) != NULL)
{
if(strstr(buf,match) !=NULL)
{
strncpy(subfile, strstr(buf,"<")+1, strstr(buf,">")-strstr(buf,"<")-1);
printf("subfile = %s\n", subfile);
sleep(3);
process_line(subfile);
memset(subfile,'\0',MAXLINE);
}
printf("%s\n", buf);
memset(buf, '\0', MAXLINE);
}
}
阅读(959) | 评论(0) | 转发(0) |