函数介绍
头文件:
#include <dirent.h>
函数定义:
int scandir(const char *dirp, struct dirent ***namelist,
int (*filter)(const struct dirent *),
int (*compar)(const struct dirent **, const struct dirent **));
返回值:
成功,返回选定的目录条目数. 失败,返回-1;
通过设置errno,获取错误原因.
测试代码:testScandir.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <dirent.h>
#include <errno.h>
#define FILELISTPAGESIZE 8
int filterRules(const struct dirent *pDirent)
{
char *pTempStr = NULL;
if (pDirent->d_type != DT_REG) {
return 0;
}
if (NULL != (strstr(pDirent->d_name, "file"))) {
if (NULL != (pTempStr = strstr(pDirent->d_name, ".dat"))) {
if (strlen(pTempStr) == strlen(".dat")) {
return 1;
}
}
}
return 0;
}
void FileListFolder()
{
int iFileCnt, iIdx, iCount, iPageIdx = 0;
struct dirent **pFileNameList;
char cHandleStr[128] = "";
memset(cHandleStr, 0x00, sizeof(cHandleStr));
if ((iFileCnt = scandir("/tmp", &pFileNameList, filterRules, alphasort)) < 0) {
perror("scandir error!!!");
} else {
if (iFileCnt > 0) {
iCount = FILELISTPAGESIZE;
if (!iPageIdx) {
iCount = iIdx = iFileCnt;
} else if (iFileCnt >= (iPageIdx - 1)*FILELISTPAGESIZE) {
iIdx = iFileCnt - (iPageIdx - 1) * FILELISTPAGESIZE;
} else {
iIdx = iFileCnt - (iFileCnt / FILELISTPAGESIZE) * FILELISTPAGESIZE;
}
while (iIdx-- && iCount > 0) {
iCount--;
strcpy(cHandleStr, pFileNameList[iIdx]->d_name);
if(NULL != strstr(cHandleStr, "file")) {
printf("file list: %s\n", cHandleStr);
} else {
printf("no file list\n");
}
free(pFileNameList[iIdx]);
}
free(pFileNameList);
}
else {
printf("empty....\n");
}
}
}
int main()
{
FileListFolder();
return 0;
}
测试结果:
root@ubuntu:tmp# gcc scandir.c
root@ubuntu:tmp# ./a.out
file list: file99.dat
file list: file02.dat
file list: file01.dat
file list: file.dat