递归打印头文件

来自:【数据结构与算法分析——C语言描述】练习1.4

题目:C提供形如 #include filename 的语句,它读入文件filename并将其插入到include语句处。include语句可以嵌套;换句话说,文件filename本身还可以包含include语句,但是显然一个文件在任何链接中都不能包含它自己。编写一个程序,使它读入被include语句修饰的一个文件并且输出这个文件。

思路:

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);
}

注意:有的头文件虽然在标准库有定义,但是基于不同的编译器,可能反倒不存在。所以对个别头文件,会出现打开文件失败的情况。

 

posted @ 2016-09-12 01:47  mingc  阅读(1319)  评论(1编辑  收藏  举报