Linux下遍历文件夹功能实现代码——20110802

这是一个实现Linux下遍历指定目录及其子目录,查找.mp4和.264文件的代码。通过调用search函数,可以打印出匹配文件的完整路径,已通过测试。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <stdio.h>
#include <malloc.h>
#include <iostream>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <time.h>
#include <dirent.h> 
#include <sys/stat.h>
#include <errno.h> 
#include <sys/types.h>

long ndir, nfile; 
int isdir(char *); 
void search(char *, char *); 

//判断是否为路径
int  isdir(char *name) 
{ 
	struct stat stbuf; 
	if(lstat(name, &stbuf) < 0)     
	{ 
		//printf( "stat:%s:%s\n",name, strerror(errno)); 
		return 0; 
	} 
	else 
		return (S_ISDIR(stbuf.st_mode))? 1 : 0; 
} 


//遍历文件夹判断是否为视频文件,为视频文件则从视频文件中获取数据
void search(char * path, char * fname) 
{ 
	DIR *dirp; 
	struct dirent *dir; 
	char buffer[BUFSIZ]; 
	char filepath[256] = "";
	if(isdir(path))   
	{ 
		if((dirp = opendir(path)) == NULL)   
		{ 
			printf( "Error opening dir %s", path); 
			printf( ":%s\n",strerror(errno)); 
			return; 
		} 
	} 
	else 
		return; 
	while((dir = readdir(dirp))!= NULL)   
	{ 
		if(!strcmp(dir-> d_name,".") || !strcmp(dir-> d_name,".."))
		{   
			//nothing
		} 
		else 
		{ 
			bzero(buffer, sizeof(buffer)); 
			strncat(buffer, path, sizeof(buffer)); 
			if(path[strlen(path)- 1]   == '/')
			{
				//noting
			}
			else 
				strncat(buffer, "/", sizeof(buffer));                     
			strncat(buffer, dir->d_name, sizeof(buffer));               
			if(isdir(buffer)) 
			{ 
				ndir++; 
				search(buffer, fname); 
			} 
			else   
			{ 
				nfile++; 
				string filename(dir->d_name);
				int nResult1=filename.find(".mp4");
				int nResult2=filename.find(".264"); 
				if(nResult1>0 || nResult2>0)
				{                                     
					printf("found:%s/%s\n",path,dir->d_name); 
					sprintf(filepath,"%s/%s",path,dir->d_name);
					//从视频文件中
					//Demo_GetStream_VideoFile(filepath);  
				} 
			} 
		} 
	} 
	closedir(dirp); 
}


使用方法:
直接调用search(char * path, char * fname)函数即可,注:fname暂时不起作用,调用的时候可以为空,该函数的作用是寻找path目录(包括子目录)下后缀名为“.mp4”或者“.264”的文件,并将文件全路径打印到屏幕。
测试通过。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值