2

几个小时以来,我一直试图在这个问题上绞尽脑汁。

我正在尝试编写一个脚本,该脚本将在一组源 *.cpp 文件中最后一次出现现有包含文件后插入一个额外的包含文件和注释。源文件位于一组递归目录中,所以我想我的脚本必须从查找开始。

比如之前:

#include <a>
#include <b>
#include <c>
// source code...

后:

#include <a>
#include <b>
#include <c>
// This is the extra include file
#include <d>
// source code...
4

3 回答 3

1

你的问题很模糊。所以我会分解你需要做的事情。

  1. 查找包含的末尾在哪里(正则表达式,手写函数)。
  2. 将原文分成两部分。
  3. 头部 + 你的包含 + 尾部 = 新文本。
  4. 将新文本写入临时文件。
  5. 删除旧文件。
  6. 将临时文件重命名为旧文件名。

您可以为此使用 C++,并且 boost(以及 c++11)具有您需要的所有抽象。

于 2013-05-29T14:40:20.493 回答
1

您可以在 python 中执行此操作,我在下面制作了一个示例脚本:

import os

def find_last_include(file_name):
    """ Returns last line with an include statement at the start """
    last_include_line = 0
    with open(file_name, "r") as f:
        for i,line in enumerate(f):
            if line.strip().startswith("#include"):
                last_include_line = max(i, last_include_line)
    return last_include_line



def insert_line(file_name, last_include_line_no, new_line):
    """ New line should end with \n"""
    try:
        with open(file_name,"r+") as f:
            print "Opening: {0}".format(file_name)
            # File is all the lines in the file as a list
            file = f.readlines()
            # last include line is the line we are going to replace the last inculde
            # with the last include + the new line we want
            last_include_line = file[last_include_line_no] + new_line
            file[last_include_line_no] = last_include_line
            print "Inserting: '{0}' On line: {1}".format(new_line.strip(), last_include_line_no)
            f.seek(0)  # Seek back to the start of the file
            for line in file:
                f.write(line)  # Write the lines with changes to the file
    except IOError as e:
        print e
    return None


if __name__ == '__main__':
    c_files = find_all(".c","Y:\\Python Stuff")
    line =  "#include <c>\n"
    for c_file in c_files:
        insert_line(c_file, find_last_include(c_file), line)
    print "Finished Inserting lines"

这打印:

SEARCHING FOR FILES..
FOUND FILE: Y:\Python Stuff\prog.c
Finished finding
Opening: Y:\Python Stuff\prog.c
Inserting: #include <c> On line: 34
Finished Inserting lines

这样做是从给定文件夹开始查找所有“.c”文件,然后查找最后一个包含所在的行并将该行添加到该行并重写文件。奇迹般有效。不过,任何改进意见将不胜感激。

于 2013-05-29T14:50:05.270 回答
0

我相信你现在已经发现这个问题的难点在于“在最后一次发生之后”。它让我想起了在同一个城镇生活了 87 年的爷爷,他偶尔会给出指示,比如“我们距离 Main St 的最后一个加油站只有一个街区”。除非您对 Main St. 了解得足够清楚,知道最后一个车站是 76 号,否则您可能会在下一个城镇最终想知道是否还有另一个加油站即将到来。

那么解决方案是什么?理论上,最后一次出现的包含可能是文件的最后一行。因此,您需要进行第一次遍历并将整个文件读入内存,以跟踪最后一个包含行发生的位置。然后第二遍写出每一行,直到最后一次出现,写下你的附加包含,然后是其余的行。

我相信,在流媒体庄园中有一些方法可以做到这一点,但它们仍然需要两次通过您的数据。另一方面,这显然是一个源代码文件,这意味着它相当小并且很容易放入内存中。

但是,了解一些典型的源代码模式后,您可能能够避免寻找第一次出现的 include ...存在的行并在它之前插入新的包含。

于 2013-05-29T15:50:01.650 回答