2012-04-16 3 views
-1

주어진 폴더를 통과하고 regex_search를 사용하여 특정 문자열의 모든 인스턴스를 찾는 프로그램을 작성해야합니다. 내가 지금 regex_search 작업을 가지고 있고, 각 파일을 어떻게 처리하는지 알아 내려고하고있다. 나는 그것을 디렉토리를 사용하여 시도하고 싶지만 내가 어디에 놓을 지 확신 할 수 없다. 파일을 통해 내 주 방법으로 검색을 수행해야합니까, 아니면 각 파일을 거치고 주 방법 내에서 호출하기 위해 주 메서드 외부에서 별도의 함수를 만들어야합니까?폴더의 각 파일에 정규식 검색 적용

이것은 내가 지금 가지고있는 것입니다. 이 팁에 접근하는 방법에 대한 조언을 주시면 감사하겠습니다!

지금은 입력 텍스트 파일을 읽고 각 인스턴스의 모든 인스턴스와 줄 번호를 표시하는 txt 파일을 출력하는 기능이 있습니다. 필자는 그들이 어떤 행을 볼 것인지, 특정 파일을 사용할 것인지,이 프로그램의 출력 파일을 만들지는 모르겠다. 찾은 내용은 단순히 콘솔에 출력된다. 나는 내가 가지고있는 것을 남겨 두었습니다. 왜냐하면 똑같은 방식으로 각 개별 파일을 똑같은 이름으로 검사 할 지 확신 할 수 없기 때문입니다.

#include <iostream> 
#include <regex> 
#include <string> 
#include <fstream> 
#include <vector> 
#include <regex> 
#include <iomanip> 

using namespace std; 

int main (int argc, char* argv[]){ 

// validate the command line info 
if(argc < 2) { 
    cout << "Error: Incorrect number of command line arguments\n" 
      "Usage: grep\n"; 
    return EXIT_FAILURE; 
} 

//Declare the arguments of the array 
    string resultSwitch = argv[1]; 
string stringToGrep = argv[2]; 
string folderName = argv [3]; 
regex reg(stringToGrep); 


// Validate that the file is there and open it 
ifstream infile(inputFileName); 
if(!infile) { 
    cout << "Error: failed to open <" << inputFileName << ">\n" 
      "Check filename, path, or it doesn't exist.\n"; 
    return EXIT_FAILURE; 
} 



while(getline(infile,currentLine)) 
{ 
    lines.push_back(currentLine); 
      currentLineNum++; 
      if(regex_search(currentLine, reg)) 
        outFile << "Line " << currentLineNum << ": " << currentLine << endl; 



} 

    infile.close(); 
} 
+0

왜'lines' 벡터 : 유닉스/리눅스/맥 OS 세계에서, 당신은 opendir()readdir()을 사용할 수 있습니까? 너는 그것을 사용하지 않고있다. – m0skit0

+0

예, 스위치를 없애고 몇 가지를 변경했습니다. 스위치가 있어야하기 때문에 스위치가 필요합니다. 그들은 내 마지막 관심사 일뿐입니다. – Sh0gun

+0

당신은 프로그램의 구조에 대해 묻고 있습니까? 유연한 코드를 원하면 모든 논리 구조/단계를 분리해야합니다. 그래서'readFolder','readFile','SearchInFile'이 가장 좋습니다. 또한 클래스에 대해 알고 있다면 OO 설계된 코드를 작성하십시오 – gaussblurinc

답변

3

디렉토리/폴더 읽기는 운영 체제에 따라 다릅니다.

#include <sys/types.h> 
#include <dirent.h> 

...

DIR *directory = opendir(directoryName); 

if(directory == NULL) 
    { 
    perror(directoryName); 
    exit(-2); 
    } 
// Read the directory, and pull in every file that doesn't start with '.' 

struct dirent *entry; 
while(NULL != (entry = readdir(directory))) 
{ 
// by convention, UNIX files beginning with '.' are invisible. 
// and . and .. are special anyway. 
    if(entry->d_name[0] != '.' ) 
     { 
     // you now have a filename in entry->d_name; 
     // do something with it. 
     } 
} 
+0

이것은 #include 을 사용해야합니까? – Sh0gun

+0

예. 위에 추가되었습니다. – DRVic