2015-06-02 35 views
0

我遇到的情況,我有各種各樣的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上,一切都很好。這也是爲什麼我主要不想使用正則表達式,因爲我需要一個額外的庫。而這只是爲了對一些文件中的一個宏作出反應似乎有點矯枉過正。

什麼是一個很好的方法使這可能工作?

+2

我不會用C++這一點,但一個腳本語言 – P0W

+0

我會用'grep'。你能澄清你爲什麼要爲此寫一個工具嗎?看起來您的主要目的是識別包含此宏的源文件並可能將其刪除。 – paddy

回答

1

我能想到的最簡單的方法是使用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'; 
     } 
    } 
} 
+0

整潔!我不知道'getline'有這樣的權力。 :) –

相關問題