简体   繁体   English

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

[英]Open a file using full path in C++

quick question really that has me momentarily stumped. 简短的问题确实让我一时难过。 This program searches through aa file directory and all of its sub directories. 该程序搜索文件目录及其所有子目录。 When it gets to a file that's not a directory type I want to open the file, throw it in a buffer and compare it to another file which will already be in another buffer. 当它到达一个不是目录类型的文件时我想打开文件,把它扔到缓冲区并将它与另一个已经在另一个缓冲区中的文件进行比较。 The problem is that the file fails to open giving me an errno that the file or directory does not exist. 问题是该文件无法打开,给我一个文件或目录不存在的错误。 My assumption is that is it trying to open the file by only its file name rather than the whole path. 我的假设是它试图仅通过文件名而不是整个路径打开文件。 How would I pull in the whole path then? 那我怎么拉进整条路呢? I have tried a few things which ultimately lead to compiling errors. 我尝试了一些最终导致编译错误的事情。 can anyone give me a quick pointer? 谁能给我快速指点?

#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);
}

连接它们:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM