c++ 获取指定文件夹下的所有文件名

std::vector<std::string> getFiles(std::string path)
{
    std::vector<std::string> files;

	//检查path是否是有效的目录
    struct stat s;
    lstat(path.data() , &s );
    if( ! S_ISDIR( s.st_mode ) )
    {
        std::cout <<"dir_name is not a valid directory !"<< std::endl;
    }

    struct dirent * filename;    // return value for readdir()
    DIR * dir;                   // return value for opendir()
    dir = opendir(path.data());
    if( NULL == dir )
    {
        std::cout<<"Can not open dir "<< path << std::endl;
    }
    std::cout <<"Successfully opened the dir !" << std::endl;

 	  //读取该目录下所有的文件名
    while( ( filename = readdir(dir) ) != NULL )
    {
  	  //跳过. 和..文件夹
        if( strcmp( filename->d_name , "." ) == 0 ||
                strcmp( filename->d_name , "..") == 0    )
            continue;
        //存入所有文件名
        std::string name(filename ->d_name);
        std::cout << name << std::endl;
        files.push_back(name);
    }
    return files;
}

猜你喜欢

转载自blog.csdn.net/weixin_42439026/article/details/88774369