码迷,mamicode.com
首页 > 编程语言 > 详细

数据结构与算法分析(C语言描述)习题1.4

时间:2016-09-12 06:07:20      阅读:1282      评论:0      收藏:0      [点我收藏+]

标签:

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

思路:

1.函数printHeadfile()接受一个文件路径,并打开该路径文件。

2.成功打开后,不断读入文件内一行数据buf。如果该行是一个“#include ”指令行,则由printHeadfile()打开并输出该子文件内容后,输出当前数据行buf(“#include ”指令行)。

3.读入下一行数据。直到读取不到,关闭文件。结束。

实现:

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <string.h>
 4 
 5 #define SIZE 1024
 6 
 7 void printHeadfile(char * filePath);
 8 
 9 int main(void)
10 {
11     printHeadfile("d:\\Program Files (x86)\\Microsoft Visual Studio 12.0\\VC\\include\\stdio.h");
12     system("pause");
13     return 0;
14 }
15 
16 /*递归打印头文件*/
17 void printHeadfile(char * filePath)
18 {
19     FILE * fp;
20     char subName[SIZE], buf[SIZE], subPath[SIZE] = "d:\\Program Files (x86)\\Microsoft Visual Studio 12.0\\VC\\include\\";
21     char * pos;
22     int size;
23 
24     if (fopen_s(&fp, filePath, "r"))
25     {
26         fprintf(stderr, "Open file failed: %s", filePath);
27         return;
28     }
29 
30     while (fgets(buf, SIZE, fp) != NULL)
31     {
32         if (strstr(buf, "#include "))
33         {
34             if (strchr(buf, <))
35             {
36                 pos = strchr(buf, <) + 1;
37                 size = strchr(buf, >) - strchr(buf, <) - 1;
38             }
39             else if (strchr(buf, \"))
40             {
41                 pos = strchr(buf, \") + 1;
42                 size = strrchr(buf, \") - strchr(buf, \") -1;
43             }
44             strncpy_s(subName, SIZE, pos, size);
45             strcat_s(subPath, SIZE, subName);
46             printHeadfile(subPath);
47             memset(subName, 0, SIZE);
48             strcpy_s(subPath, SIZE, "d:\\Program Files (x86)\\Microsoft Visual Studio 12.0\\VC\\include\\");
49         }
50         fputs(buf, stdout);
51     }
52     fclose(fp);
53 }

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

数据结构与算法分析(C语言描述)习题1.4

标签:

原文地址:http://www.cnblogs.com/mingc/p/5863393.html

(1)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!