使用C ++中的完整路径打开文件

时间:2011-10-15 05:30:55

标签: c++ directory

快速的问题确实让我暂时难过。该程序搜索文件目录及其所有子目录。当它到达一个不是目录类型的文件时我想打开文件,把它扔到缓冲区并将它与另一个已经在另一个缓冲区中的文件进行比较。问题是该文件无法打开,给我一个文件或目录不存在的错误。我的假设是它试图仅通过文件名而不是整个路径打开文件。那我怎么拉进整条路呢?我尝试了一些最终会导致编译错误的东西。谁能给我一个快速指针?

#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 个答案:

答案 0 :(得分:3)

连接它们:

open((path + "/" + dir_entry->d_name).c_str(), ...)
相关问题