Skip to content

Instantly share code, notes, and snippets.

@cosmo0920
Created May 30, 2012 14:35
Show Gist options
  • Save cosmo0920/2836691 to your computer and use it in GitHub Desktop.
Save cosmo0920/2836691 to your computer and use it in GitHub Desktop.
C++で正規表現使ってファイルの中からgrepしよう。出典:http://itpro.nikkeibp.co.jp/article/COLUMN/20071024/285414/?ST=oss&P=3
#include <iostream>
#include <fstream>
#include <cstring>
#include <cstdlib>
#include <boost/regex.hpp>
//このファイルの情報を元に検索を行う
const char filename[] = "filename.txt";
//出力をする関数たち
template <typename T>
void displayUsage(const T* message)
{
std::cout << "\x1b[31m" << "Usage: make filename.txt" << std::endl
<< "and then" << message << " string" << "\x1b[m" << std::endl;
}
template <typename T>
void display_filename(const T* message)
{
std::cout << "\x1b[32m" << message << "\x1b[m" << std::endl;
}
template <typename T>
void display_line_num(const T message)
{
std::cout << "\x1b[36m" << message << "\x1b[m";
}
template <typename T,typename P>
void display_search_word(const T message, const P regex)
{
//正規表現で探している文字を強調するよ
std::cout << regex_replace( message, regex, "\x1b[31m$&\x1b[m",
boost::format_all )
<< std::endl;
}
int main(int argc, char *argv[])
{
FILE *fp, *fin;
char line[128], src[1024];
int len, flen, slen, i, lno, flag;
//バッファとか正規表現用
std::string str,s;
if(argc!=2) {
displayUsage(argv[0]);
return EXIT_FAILURE;
}
//正規表現の準備
s=argv[1];
boost::regex re(s);
flen=strlen(argv[1]);
fp=fopen(filename, "r");
if(!fp){
displayUsage(argv[0]);
return EXIT_FAILURE;
}
while(fgets(line, 128, fp)){
len=strlen(line);
line[len-1]='\0';
fin=fopen(line, "r");
if(!fin){
return EXIT_FAILURE;
}
lno=1;
flag=0;
while(fgets(src, 1024, fin)){
src[strlen(src)-1]='\0';
slen=strlen(src);
for(i=0; i<slen; i++){
if(!strncmp(&src[i], argv[1], flen)){
if(flag==0){
display_filename(line);
flag=1;
}
str=src;//char -> std::string
display_line_num(lno); display_search_word(str,re);
}
}
lno++;
}
fclose(fin);
}
fclose(fp);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment