/* * diffregex.cc * 第1ファイルをregex として、第2ファイルと diff する。 * Sat,18 Oct,2008 * * Copyright(C)2008 G-HAL */ #include #include #include #include #define MAX_BUF 1024 #define MAX_MATCH 10 #if !defined(__unused) # if defined(ATTRIBUTE_UNUSED) # define __unused ATTRIBUTE_UNUSED # else # define __unused __attribute__ ((__unused__)) # endif #endif # define _number_(arr) (sizeof(arr)/sizeof((arr)[0])) struct Line { public: bool hit; int num; char* msg; Line* next; static void free( Line* ptr ) { while (ptr) { Line* const next = ptr->next; delete[] ptr->msg; delete ptr; ptr = next; } } }; bool diffregex( Line* f1, Line* f2 ) { bool match_flag = true; regex_t reg; regmatch_t match[MAX_MATCH]; char err_msg[MAX_BUF]; char buf[MAX_BUF]; for ( ; f1; f1 = f1->next) { snprintf( buf, _number_(buf), "^%s$", f1->msg ); const int ret_regcomp = regcomp( ®, buf, REG_EXTENDED ); if (ret_regcomp) { regerror( ret_regcomp, ®, err_msg, _number_(err_msg) ); fprintf(stderr, "%d: ERROR in regcomp() :%s\n", f1->num, err_msg ); continue; } f1->hit = false; for ( Line* ptr = f2; ptr; ptr = ptr->next) { if (ptr->hit) { continue; } const int ret_regexec = regexec( ®, ptr->msg, _number_(match), match, 0 ); if (0 == ret_regexec) { f1->hit = true; ptr->hit = true; break; } } regfree( ® ); if (!f1->hit) { printf("%d<%s", f1->num, f1->msg ); match_flag = false; } } for ( ; f2; f2 = f2->next) { if (!f2->hit) { printf("%d>%s", f2->num, f2->msg ); match_flag = false; } } return match_flag; } Line* const fread_file( FILE* const fp ) { char buf[MAX_BUF]; int line_num = 0; Line init = { false, 0, NULL, NULL }; Line* ptr = &init; while (!feof(fp)) { buf[0] = '\0'; fgets( buf, _number_(buf), fp ); line_num++; if ('\0' == buf[0]) { break; } ptr->next = new Line; ptr->next->hit = false; const size_t line_len = strlen(buf) + 1; ptr->next->num = line_num; ptr->next->msg = new char[line_len]; memcpy( ptr->next->msg, buf, line_len ); ptr->next->next = NULL; ptr = ptr->next; } return init.next; } int main( __unused int argc, __unused const char* argv[], __unused const char* env[] ) { if ((argc < 3) || (3 < argc)) { fprintf(stderr, "Too few/many argment.\n" ); return -1; } FILE* const fp1 = fopen( argv[1], "r" ); FILE* const fp2 = fopen( argv[2], "r" ); Line* const f1 = fread_file( fp1 ); Line* const f2 = fread_file( fp2 ); fclose( fp1 ); fclose( fp2 ); const bool ret = diffregex( f1, f2 ); f1->free( f1 ); f2->free( f2 ); return ret ? 0 : 1; } /* [ End of File ] */