思路:
1.函数printHeadfile()接受一个文件路径,并打开该路径文件。
2.成功打开后,不断读入文件内一行数据buf。如果该行是一个“#include ”指令行,则由printHeadfile()打开并输出该子文件内容后,输出当前数据行buf(“#include ”指令行)。
3.读入下一行数据。直到读取不到,关闭文件。结束。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 1024
void printHeadfile(char * filePath);
int main(void)
{
printHeadfile("d:\\Program Files (x86)\\Microsoft Visual Studio 12.0\\VC\\include\\stdio.h");
system("pause");
return 0;
}
/*递归打印头文件*/
void printHeadfile(char * filePath)
{
FILE * fp;
char subName[SIZE], buf[SIZE], subPath[SIZE] = "d:\\Program Files (x86)\\Microsoft Visual Studio 12.0\\VC\\include\\";
char * pos;
int size;
if (fopen_s(&fp, filePath, "r"))
{
fprintf(stderr, "Open file failed: %s", filePath);
return;
}
while (fgets(buf, SIZE, fp) != NULL)
{
if (strstr(buf, "#include "))
{
if (strchr(buf, '<'))
{
pos = strchr(buf, '<') + 1;
size = strchr(buf, '>') - strchr(buf, '<') - 1;
}
else if (strchr(buf, '\"'))
{
pos = strchr(buf, '\"') + 1;
size = strrchr(buf, '\"') - strchr(buf, '\"') - 1;
}
strncpy_s(subName, SIZE, pos, size);
strcat_s(subPath, SIZE, subName);
printHeadfile(subPath);
memset(subName, 0, SIZE);
strcpy_s(subPath, SIZE, "d:\\Program Files (x86)\\Microsoft Visual Studio 12.0\\VC\\include\\");
}
fputs(buf, stdout);
}
fclose(fp);
}