数据结构与算法分析(C)习题1.4解答.
来源:互联网 发布:胡宗南保卫延安知乎 编辑:程序博客网 时间:2024/06/08 08:42
原题是这样的:
1.4 C allows statements of the form
#include filenamewhich reads filename and inserts its contents in place of the include statement. Include statements may be nested; in other words, the file filename may itself contain an include statement, but, obviously, a file can't include itself in any chain. Write a program that reads in a file and outputs the file as modified by the include statements.
没太看懂, 与是找到中文版:
我怀疑翻译的人也没看懂.
直到我看到英文答题提示,
The general way to do this is to write a procedure with heading
void ProcessFile( const char *FileName );
which opens FileName,O does whatever processing is needed, and then closes it. If a line of the form
#include SomeFile is detected, then the call
ProcessFile( SomeFile );
is made recursively. Self-referential includes can be detected by keeping a list of files for which a call to ProcessFile has not yet terminated, and checking this list before making a new call to Process File.
其实就是把一个文件的#include语句用其包含的文件内容替换,而被包含的文件中可能还有#include,如果把include看成一个函数的话,其实就是一个递归。
理解了题目就好答了,由于对C掌握得不好,费半天劲才调通,主要是文件名的计算上没考虑到最后一行少一个换行符。
程序如下, 不完备,只显示思路。
没考虑找不到文件与循环包含情况下的错误处理, 只是在理想情况下, 顺序打印出每一行, 没将其存入一个文件.
void ProcessFile(const char* filename)
{
char buff[1024];
FILE* fp = fopen(filename, "r");
char temp_name[30];
while(!feof(fp))
{
//依次读取文件行.
fgets(buff, 1024, fp);
// 如果某行中有#include, 则找到后面的文件名. 将其存入temp_name, 然后用移位的方法消除双引号.
if (strstr(buff, "#include") != NULL)
{
// 将引号后面的内容拷贝到temp_name
strcpy(temp_name, strstr(buff, "\""));
int i = 0;
// 将temp_name每个成员向前移一位, 消除前面引号.
while (temp_name[i] != '\0') {
temp_name[i] = temp_name[i + 1];
i++;
}
// 用'\0'覆盖后面的引号, 因为最后一行少一个换行符,所以少1位.
if (feof(fp)) {
temp_name[i - 2] = '\0';
}
else
{
temp_name[i - 3] = '\0';
}
//递归调用计算找的文件;
ProcessFile(temp_name);
}
else
{
//打印每一行.
printf("%s\n", buff);
}
// 清除buff数据, 避免当最后一行为空行时重复打印上一行
buff[0] = '\0';
}
fclose(fp);
}
int main()
{
ProcessFile("test.h");
getchar();
return 0;
}
网上这道题的解答我只找到2个,没看懂(水平太低,刚学完C语法,正学data structures and algorithm analysis in c)。
- 数据结构与算法分析(C)习题1.4解答.
- 数据结构与算法分析(C)习题1.5解答 证明 log x < x
- 数据结构与算法经典习题解答
- 《算法设计与分析》习题解答笔记
- 数据结构和算法分析习题解答之一——引言
- 数据结构和算法分析习题解答之二——第1章习题解答
- 数据结构与算法分析 习题1.1
- 算法设计与分析习题2的部分解答
- 算法设计与分析复习(一):习题解答
- 数据结构与算法分析(C)1.4
- 数据结构与算法分析(C语言版)第二章习题2.7代码实现
- 数据结构与算法设计 习题2.7题 算法分析
- 数据结构与算法分析c++:算法分析
- 数据结构与算法分析c++:算法分析
- 数据结构与算法分析课后习题第三章(2)
- 数据结构与算法分析课后习题第三章(3)
- 数据结构与算法分析课后习题第三章(4)
- 数据结构与算法分析课后习题第三章(5)
- 菜鸟学java第一天
- CodeForces
- OpenFace: an open source facial behavior analysis toolkit
- hdu1827 Summer Holiday(强连通,缩点建图)
- ConfigReader(十一)—— ReadGuideCameraTaskConfig
- 数据结构与算法分析(C)习题1.4解答.
- python实现json文件中向量写入Excel中
- ViewPager循环滑动
- Codeforces Round #439 C.The Intriguing Obsession(组合数学)
- webpack之前的各种工具
- Spring Data Jpa Like查询问题
- 关联容器(map、set、multimap、multiset、pair、unordered_map)
- 循环控制
- Brackets sequence UVA