前言

我们知道#include可以引入文件,又可推知,引入的文件中还能包含#include,再次引入文件。即,引用文件中的文件。

  • 我们可以使用递归来输出所有引入文件的内容

函数

strstr()

  • 参数
    (s1, s2)

  • 返回值
    返回s2的首字符地址,找不到返回NULL

  • 作用
    从字符串s1中找到字符串s2

strchr()

  • 参数
    (s1, c1)

  • 返回值
    返回s1中c1的字符地址

  • 作用
    从s1中查找c1字符

  • 注意
    调用字符串与首元素地址,紧密联系即,以上s1,s2都是字符串的首元素地址

实现

filename.c
1
2
3
4
5
6
7
#include<stdio.h>
#include<stdlib.h>
#include "add.c"
void Print()
{
printf("Hello");
}
add.c
1
2
3
4
5
6
#include<stdio.h>

void add()
{
printf("Hi");
}
main文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include "filename.c"
#include <string.h>
#define SIZE 256
void ProcessFile(const char * Filename)
{
char line[SIZE];
char f_name[SIZE];

FILE * fp;
char ch;
if((fp = fopen(Filename, "r")) == NULL)
{
fprintf(stderr, "Could not open %s\n", Filename);
exit(EXIT_FAILURE);
}
while((ch = getc(fp)) != EOF)
putc(ch, stdout);
printf("\n");

//开始查找文件中的文件
rewind(fp);
while (fgets(line, SIZE, fp) != NULL)
{
if(strstr(line, "#include \"") )
{
char *find = strchr(&line[10], '\"');//先找到最后的"在字符串中出现的指针
*find = '\0'; //再替换为'\0',得到文件名

ProcessFile(&line[10]); //递归调用该函数
}
}

fclose(fp);
}

int main()
{

ProcessFile("filename.c");
return 0;
}