数据结构与算法分析(C)习题1.4解答.

原题是这样的:

1.4 C allows statements of the form

#include filename

which 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解答.)