在没有正则表达式的情况下选择特定的字符串模式

Picking up a certain string pattern without regex

我有一个场景,我有各种带有特定宏的 C++ 文件:

__EXTERNALIZE(Name, File)

这个宏是空的,它什么都不做。但是我想编写一个外部工具来扫描这个宏的一个或多个输入文件,并在找到后做一些事情。

为了澄清,这里有一点伪 C:

typedef struct {
    char* varname;
    char* filename;
} MacroInfo_s;
FILE* fh = fopen("./source.cpp",'r');
while(read_untill_macro(fh) && !feof(fh)) {
    MacroInfo_s m;
    fill_macro_info(&m, fh);
    // Do something with m.varname and m.filename
}

C++11 并未广泛使用。例如,VS 2010 根本不提供它,这是我想要在 Windows 端定位的最低值。在我的 OS X 10.10 上,一切都很好。这也是我主要不想使用 Regexp 的原因,因为我需要一个额外的库。仅仅对几个文件中的单个宏做出反应似乎有点矫枉过正。

使这成为可能的好方法是什么?

我能想到的最简单的方法是使用 std::getline 读取每个打开的括号 (,然后检查该字符串是否适合您的宏。

然后另一个 std::getline 阅读结束括号 ) 应该提取宏的参数。

有点像这样:

const std::string EXTERNALIZE = "__EXTERNALIZE";

int main(int, char* argv[])
{
    for(char** arg = argv + 1; *arg; ++arg)
    {
        std::cout << "Processing file: " << *arg << '\n';

        std::ifstream ifs(*arg);

        std::string text;
        while(std::getline(ifs, text, '('))
        {
            // use rfind() to check the text leading up to the open paren (
            if(text.rfind(EXTERNALIZE) != text.size() - EXTERNALIZE.size())
                continue;

            std::cout << "found macro:" << '\n';

            // now read the parameters up to the closing paren )
            std::getline(ifs, text, ')');

            // here are the macro's parameters
            std::cout << "parameters: " << text << '\n';
        }
    }
}