C语言:scandir函数用法:枚举目录中指定的文件

函数介绍

头文件:
   #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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值