DIR和dirent 用来获取某文件夹目录内容的结构体
DIR结构体:
struct __dirstream
{
void *__fd;
char *__data;
int __entry_data;
char *__ptr;
int __entry_ptr;
size_t __allocation;
size_t __size;
__libc_lock_define (, __lock)
};
typedef struct __dirstream DIR;
函数 DIR *opendir(const char *pathname),即打开文件目录,返回的就是指向DIR结构体的指针,而该指针由以下几个函数使用:
struct dirent *readdir(DIR *dp);//读取到的文件名存储在结构体dirent的d_name成员中
void rewinddir(DIR *dp);
int closedir(DIR *dp);
long telldir(DIR *dp);
void seekdir(DIR *dp,long loc);
dirent结构体:
#include <dirent.h>
struct dirent
{
long d_ino; /* inode number 索引节点号 */
off_t d_off; /* offset to this dirent 在目录文件中的偏移 */
unsigned short d_reclen; /* length of this d_name 文件名长 */
unsigned char d_type; /* the type of d_name 文件类型 */
char d_name [NAME_MAX+1]; /* file name (null-terminated) 文件名,最长256字符 */
}
代码实例:
获取二级目录下所有与.png文件同名的.pb文件列表
void readInputFileList(std::string in_dir, std::vector<std::string> &file_list)
{
DIR *dir = NULL;
if ((dir = opendir(in_dir.c_str())) == NULL)
std::cout << in_dir << ": Open dir failed." << std::endl;
struct dirent *ptr;
while (ptr = readdir(dir))
{
if (ptr->d_name[0] == ".")
continue;
else if (ptr->d_type == DT_DIR)
{
std::string path = in_dir + "/";
path += ptr->d_name;
DIR *d = NULL;
if ((d = opendir(path.c_str())) == NULL)
std::cout << path << ": Open dir failed." << std::endl;
struct dirent *p;
while (p = readdir(d))
{
if (p->d_name[0] == "." || p->d_type == DT_DIR)
continue;
std::string image_name(p->d_name);
if (image_name.substr(image_name.size() - 4) != ".png")
continue;
std::string pb_name = image_name.substr(0, image_name.size() - 3) + "pb";
std::string pb_path = path + "/" + pb_name;
if (access(pb_path.c_str(), 0) != 0)
continue;
file_list.push_back(pb_path);
}
}
else
std::cout << ptr->d_name << ": Can not contain file." << std::endl;
}
sort(file_list.begin(), file_list.end());
}声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
- 上一篇:没有了
- 下一篇:没有了
