DIR函数以及dirp函数
DIR* opendir(const char*pathname),即打开文件目录,返回的就是指向DIR结构体的指针。
返回该指针以后,就可以被以下函数来使用了,
struct dirent *readdir(DIR *dp)
int closedir(DIR *dp)
long telldir(DIR *dp)
要知道dirent结构体是什么样的:
struct dirent
{
long d_no;//索引节点号
...
char d_name;//文件名
}
通过readdir 函数读取的文件名存放到dirent结构体的d_name成员中,
而函数stat
int stat(const char *filename,struct stat *buf);的作用就是获取d_name的文件详细信息,存储在stat结构体中。
stat结构体如下
struct stat{
time_t st_atime;//最后一次访问该文件的时间
time_t st_mtime;//最后一次修改该文件的时间
time_t st_ctime;//最后一次改变该文件状态的时间
...
}
获取一个文件信息的步骤如下
opendir打开目录,返回指向该目录下所有文件的dirent结构体d。
接着,遍历d,获取每个文件的详细信息,存储在stat结构体e中。
实战例子
int OpenDir(vector<string> & fileNameVec,const string &tmp_path)
{
DIR* dp;
struct dirent* dirp;
if((dp = opendir(tmp_path.c_str())) == NULL)
{
perror( "Open dir error" );
return -1;
}
while ((dirp = readdir(dp)) != NULL)
{
if (strcmp( dirp->d_name, ".") == 0 || strcmp(dirp->d_name,"..") == 0)
{
continue;
}
if (strstr( dirp->d_name,.DT) == NULL)
{
continue;
}
string tmpfileName(dirp->d_name);
fileNameVec.push_back(tmpfileName);
if (fileNameVec.size()>10) //一次传输10个
{
closedir(dp);
return 1;
}
}
closedir(dp);
return 1;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)