2011-10-15 7 views
1

빠른 질문은 정말 저를 순간적으로 곤란하게합니다. 이 프로그램은 파일 디렉토리와 모든 하위 디렉토리를 검색합니다. 디렉토리 유형이 아닌 파일에 도달하면 파일을 열고 버퍼에 던져서 이미 다른 버퍼에있는 다른 파일과 비교하려고합니다. 문제는 파일이 열리지 않아 파일이나 디렉토리가 존재하지 않는다는 errno를 제공한다는 것입니다. 필자의 가정은 전체 경로가 아닌 파일 이름 만 사용하여 파일을 여는 것입니다. 어떻게하면 전체 경로에서 끌어낼 수 있을까요? 나는 궁극적으로 컴파일 오류로 이어질 몇 가지 시도했다. 누구든지 나에게 빠른 포인터를 줄 수 있니?C++에서 전체 경로를 사용하여 파일 열기

#include <dirent.h> 
#include <errno.h> 
#include <stdio.h> 
#include <cstdlib> 
#include <iostream> 
#include <cctype> 
#include <cstdio> 
#include <string> 
#include <list> 
#include <sys/types.h> 
#include <unistd.h> 
#include <stdio.h> 
#include <sys/stat.h> 
#include <fcntl.h> 
#include <stdlib.h> 

using std::string; 
using std::ostream; 
using std::list; 
using std::endl; 

off_t tell(int fd) { 
    return lseek(fd, 0, SEEK_END); 
} 

void dir_traverse(const std::string& path, std::ostream& out) { 
    list<string> child_directories; 
    DIR*dirp = opendir(path.data()); 
    struct dirent*dir_entry = readdir(dirp); 
    while(dir_entry !=NULL){ 
     unsigned char d_type = dir_entry->d_type==DT_DIR?'D' : 'F'; 
     if(d_type == 'D'){ 
      if(dir_entry->d_name[0]!= '.') { 
       child_directories.push_back(dir_entry->d_name); 
       out<<'\t'<<d_type<<":"<<dir_entry->d_name<<endl; 
      } 
     } 
     if(d_type == 'F'){ 

      int fd= open(dir_entry->d_name, O_RDONLY); 
      if(fd =-1){ 
      out<<"file did not open"<<'\t'<<errno<<endl; 
      } 
      int size= tell(fd); 

      out<<'\t'<<d_type<<":"<<dir_entry->d_name<<endl; 

      close(fd); 

      //open file 
      //read file 
      //compare two files 
      //print name of file and path if two are equal otherwise do nothing 

     } 
     dir_entry= readdir(dirp); 
    } 
    list<string>::iterator it = child_directories.begin(); 
    while(it != child_directories.end()) { 
     dir_traverse(path + "/" + *it, out); 
     it++; 
    } 
    closedir(dirp); 
} 

int main() { 
    dir_traverse("./homework", std::cout); 
} 
+1

빠른 포인터를? 여기에 세 가지가 있습니다 : http://xkcd.com/138/ – Johnsyweb

답변

3

를 연결할 :

open((path + "/" + dir_entry->d_name).c_str(), ...) 
+0

그것이 의미하지 않는 이유를 확신하지 못합니다. 감사 – user975044

관련 문제