2012-04-11 5 views
0

walkThroughFunction에서 재귀 호출에 문제가 있습니다. 코드는 디렉토리를 거쳐 하위 디렉토리를 계산하고 파일을 찾으면 파일을 열고 특정 문자열을 검색해야합니다. 코드는 하나의 디렉토리에만 있습니다. 누군가가 이것으로 나를 도울 수 있습니까? 중괄호가 약간 잘못 배치 된 것을 알 수 있습니다. 친절하게 무시합니다.재귀 디렉터리 및 파일 스트리밍 및 검색 문자열

int directories=0; 
void walkThroughDirectory(char *directory_name,char *searchString){ 

DIR * directory; 
struct dirent * walker; 
char d_name[PATH_MAX]; 
int path_length; 
char path[PATH_MAX]; 
directory=opendir(directory_name); 
if(directory==NULL){ 
    cout<<"Error"<<endl; 
    cout<<directory_name<<" Cannot be Opened"<<endl; 
    exit(10000); 
} 
while((walker=readdir(directory)) !=NULL){ 




    strcpy(d_name,walker->d_name); 
    cout<<directory_name<<"/"<<endl; 
    if (strcmp (d_name, "..") == 0 && 
      strcmp (d_name, ".") == 0){ 
     continue; 
    } 
    else{ 


     path_length =  snprintf(path,PATH_MAX,"%s/%s\n",directory_name,d_name); 
     cout<<"HELLO"<<endl; 
     cout<<path<<endl; 
     if (path_length >= PATH_MAX){ 
      cout<<"Path is too long"<<endl; 
      exit (1000); 
     } 
     if(walker->d_type==DT_DIR){ 
      cout<<"Hello"<<endl; 
      directories++; 
      walkThroughDirectory (path,searchString); 
     } 
     else if(walker->d_type==DT_REG){ 
      ifstream openFile; 
      openFile.open(path); 
      char line[1500]; 
      int currentLine = 0; 
      if (openFile.is_open()){ 
       while (openFile.good()){ 
        currentLine++; 
        openFile.getline(line, 1500); 
        if (strstr(line, searchString) != NULL) 
         cout<<path<<": "<<currentLine<<": "<<line<<endl; 
       } 
      } 
      openFile.close();  
     } 
     /* 
     struct stat directory_stat; 
     if (stat(path, &directory_stat) == -1){ 

      return; 
     } 
     if (S_ISDIR(directory_stat.st_mode)){ 
      cout<<"HELLO"<<endl; 

      directories++; 
      walkThroughDirectory(path, searchString); 
     } 
     else if (S_ISREG(directory_stat.st_mode)){ 

      ifstream openFile; 
      openFile.open(path); 
      char line[1500]; 
      int currentLine = 0; 
      if (openFile.is_open()){ 
       while (openFile.good()){ 
        currentLine++; 
        openFile.getline(line, 1500); 
        if (strstr(line, searchString) != NULL) 
         cout<<path<<": "<<currentLine<<": "<<line<<endl; 

       } 

      } 
      // it's a file so search for text in file 

     } 
     */ 

    } 

} 

if (closedir (directory)) 
{ 
    cout<<"Unable to close "<<directory_name<<endl; 
    exit (1000); 
} 
} 

int main(){ 

    char * name; 
    name=new char; 

    cout<<"Total Directories "<< directories<<endl; 



    name=get_current_dir_name(); 
    cout<<"Current Directory is: "<<name<<endl; 
    /* 
    cout<<"Now Enter The Desired Directory from the root or the current path"<<endl; 
    char *desiredDirectory; 
    desiredDirectory=new char; 
    cin>>desiredDirectory; 
    cout<<"Enter The String You want to search"<<endl; 
    char *searchString; 
    searchString=new char; 
    cin>>searchString; 
    */ 
    char ourpath[400]; 
    strcpy(ourpath,name); 

    walkThroughDirectory(ourpath,"diminutive"); 
    cout<<"Total Directories "<< directories<<endl; 


    return 0; 
} 
+0

왜 괄호는 틀렸습니까? 적절한 들여 쓰기 체계를 사용하면 많은 오류를 훨씬 빨리 수정할 수 있습니다. – Bojangles

+0

나는이 문제를 서둘러 해결하려고 노력하고 있었다. 그것이 프로젝트이기 때문에 가능한 빨리 돌려줘야합니다. 따라서 잘못 배치 된 것입니다. 미안 해요 .JamWaffles 도와주세요. – mobykhn

답변

0

이 코드에는 몇 가지 문제점이 있습니다. 먼저 strcmp을 수행하여 d_name이 "."인지 확인합니다. 또는 ".."인 경우 AND가 아닌 OR을 사용해야합니다. 두 번째로 sprintf을 호출하여 C 문자열 path을 만들 때 문자열 끝에 개행 문자가 없어야합니다. 이것이 코드가 한 단계 깊숙해 지도록하는 원인이었습니다. 셋째, get_current_dir_name으로 전화하면 모든 malloc이 작동합니다. 당신이하고있는 일은 하나의 char을위한 공간을 할당하는 것인데, 그것은 그 자체로는 작동하지 않을 것이고 API의 올바른 사용은 아닙니다. man page for get_current_dir_name을 참조하십시오.

아래 코드는 이러한 문제를 해결하고 적절한 들여 쓰기 기능을 제공합니다.

#include <iostream> 
#include <fstream> 
#include <stdlib.h> 
#include <unistd.h> 
#include <dirent.h> 
#include <limits.h> 
#include <string.h> 

int directories=0; 
void walkThroughDirectory(char *directory_name,char *searchString) 
{ 
    DIR *directory; 
    struct dirent *walker; 
    char d_name[PATH_MAX]; 
    int path_length; 
    char path[PATH_MAX]; 
    directory = opendir(directory_name); 

    if(directory == NULL) 
    { 
     std::cout << directory_name << " Cannot be Opened" << std::endl; 
     exit(1); 
    } 

    while((walker=readdir(directory)) != NULL) 
    { 
     strcpy(d_name, walker->d_name); 

     // Needs to be || not && 
     if (strcmp(d_name, "..") == 0 || strcmp(d_name, ".") == 0) 
     { 
      continue; 
     } 
     else 
     { 
      // No newline on the path name. 
      path_length = snprintf(path, PATH_MAX, "%s/%s", directory_name, d_name); 

      if (path_length >= PATH_MAX) 
      { 
       std::cout << "Path is too long" << std::endl; 
       exit(2); 
      } 

      if(walker->d_type == DT_DIR) 
      { 
       directories++; 
       walkThroughDirectory(path, searchString); 
      } 
      else if(walker->d_type==DT_REG) 
      { 
       std::ifstream openFile; 
       openFile.open(path); 
       char line[1500]; 
       int currentLine = 0; 

       if (openFile.is_open()) 
       { 
        while (openFile.good()) 
        { 
         currentLine++; 
         openFile.getline(line, 1500); 
         if (strstr(line, searchString) != NULL) 
         std::cout << path << ": " << currentLine << ": " << line << std::endl; 
        } 
       } 
       openFile.close();  
      } 
     } 
    } 

    if (closedir(directory)) 
    { 
     std::cout << "Unable to close " << directory_name << std::endl; 
     exit(3); 
    } 
} 

int main() 
{ 
    // get_current_dir_name() mallocs a string for you. 
    char *name; 

    name = get_current_dir_name(); 
    walkThroughDirectory(name, "matthew"); 
    free(name); 
    std::cout << "Total Directories: " << directories << std::endl; 

    return 0; 
}