Linux程序设计(14)第三章:标准I/O库(6)扫描目录: opendir closedir readdir telldir seekdir

Linux程序设计(14)第三章:标准I/O库(6)扫描目录: opendir closedir readdir telldir seekdir

1. opendir closedir readdir

#include <sys/types.h>
#include <dirent.h>
DIR *opendir(const char *name);
struct dirent *readdir(DIR *dirp);
long int telldir(DIR *dirp);
void seekdir(DIR *dirp, long int loc);
int closedir (DIR *dixrp);

2. 例子-扫描目录

#include<stdio.h>
#include<stdlib.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <stdlib.h>

int SCAN_DIR(char *pcDir, int depth)
{
	DIR *pDir = NULL;
	struct dirent *pstCurr = NULL;
	struct stat stStat;
	char szSubPath[1024];
	char *pcTail = NULL;
	
	pDir = opendir(pcDir);
	if(NULL == pDir)
	{
		printf("Error while opening dir %s", pcDir);
		return -1;
	}

	chdir(pcDir);
	
	do
	{
		pstCurr = readdir(pDir);
		if(NULL == pstCurr)
		{
			break;
		}
		
		/* .和.. 分别表示当前目录和上一级目录 */
		if((0 == strcmp(pstCurr->d_name, ".")) ||
		(0 == strcmp(pstCurr->d_name, "..")))
		{
			continue;
		}
		
		memset(szSubPath, 0, sizeof(szSubPath));
		sprintf(szSubPath, "%s/%s", pcDir, pstCurr->d_name);
		lstat(szSubPath, &stStat);
		if(S_ISDIR(stStat.st_mode))
		{
			SCAN_DIR(szSubPath,depth+4);
			printf("\r\n");
		}
		else
		{
		
			printf("%*s%s\r\n",depth,"",szSubPath);
			/* 或者对具体文件进行处理 */
		}
	}while(1);
	
	chdir("..");
	closedir(pDir);
}

int main()
{
	int res = SCAN_DIR("/home", 0);
	if(-1 == res)
	{
		printf("scan error!\r\n");
	}

	exit(0);
}

结果:

[root@localhost linux-chegnxusheji]# ./a.out 
/home/registre.c
/home/add.c
/home/add.s
/home/add.o
	/home/extern-test/main.c
	/home/extern-test/test2.h
	/home/extern-test/test1.c

	/home/semTest/set.c
	/home/semTest/a.out

/home/result
……
……

おすすめ

転載: blog.csdn.net/lqy971966/article/details/120674951