开发者

Open a file using full path in C++

开发者 https://www.devze.com 2023-04-13 09:06 出处:网络
quick question really that has me momentarily stumped. This program searches through a a file directory and all of its sub directories. When it gets to a file that\'s not a directory type I want to op

quick question really that has me momentarily stumped. This program searches through a a 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<&开发者_JS百科lt;":"<<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);
}


Concatenate them:

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

精彩评论

暂无评论...
验证码 换一张
取 消