原题是这样的:
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掌握得不好,费半天劲才调通,主要是文件名的计算上没考虑到最后一行少一个换行符。
程序如下, 不完备,只显示思路。
没考虑找不到文件与循环包含情况下的错误处理, 只是在理想情况下, 顺序打印出每一行, 没将其存入一个文件.
网上这道题的解答我只找到2个,没看懂(水平太低,刚学完C语法,正学data structures and algorithm analysis in c)。