简体   繁体   中英

opendir() throwing an instance of 'std::logic_error'

I have a path defined as std::string folder_path = "server/files/";. I am trying to list the files in a directory. I am able to successfully open the file and list the files (see console output below); however, I get the following error after the files are listed:

terminate called after throwing an instance of 'std::logic_error'
  what():  basic_string::_M_construct null not valid
Aborted

Here is what i currently came up with. I read it is something to do with string not being NULL however folder_path will have a default value anyways so I am unsure how to proceed from here:

struct dirent *entry;
struct stat filestat;

DIR *dir = opendir(folder_path.c_str());
if(dir == NULL){
    cout << "Not a valid directory: " << mount_path << endl;
}

if(errno == ENOTDIR){
    cout << "OpenDir() Error (" << strerror(errno) << ")" << dir << endl;
}

cout << "Getting files from:" << mount_path << endl;
while((entry = readdir(dir))){
    stat(entry->d_name, &filestat);
    cout << entry->d_name << " " << ctime(&filestat.st_mtime);
}

closedir(dir);

output:

Getting files from: server/files/
. Sat Nov 16 06:54:14 2019
.. Sat Nov 16 03:21:09 2019
alpha.jpg Sat Nov 16 03:21:09 2019
stockphoto.jpg Sat Nov 16 03:21:09 2019
image_fj8u3sadu3.jpg Sat Nov 16 03:21:09 2019
image_ijdalksd213.jpg Sat Nov 16 03:21:09 2019
terminate called after throwing an instance of 'std::logic_error'
  what():  basic_string::_M_construct null not valid
Aborted

Code should run fine. Try this:

      if (stat(entry->d_name, &filestat)){
            cout << entry->d_name << " " << ctime(&filestat.st_mtime);
        }else{ /* handle error here*/}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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