2011-10-15 45 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