C遍历文件夹

先上代码有空再解释

#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<dirent.h>
#include<stdio.h>
#include<unistd.h>
#include<errno.h>
#include<string>
#include<string.h>
#include<vector>
using namespace std;
void my_create();
vector<string> getFiles(string cate_dir);
int main()
{
	string cate_dir="/media/ubuntu/";
	string dir;
	vector<string> files=getFiles(cate_dir);
	int num_file = 0;
	if (!files.empty())
	{
		num_file=files.size();
		dir = cate_dir+files.front()+"/image/";
		printf("the number of files is : %d\n the final path is:%s\n",num_file,dir.c_str());
	}
	return 0;
}
void my_create()
{	
	int fd;
	if((fd=open("text.txt",O_CREAT|O_EXCL,S_IRUSR|S_IWUSR))==-1)
	{
		perror("open");
	}else
	{
		printf("create file success\n");
	}
	close(fd);
}
vector<string> getFiles(string cate_dir)
{
	vector<string> files;//存放文件名
	DIR *dir;
	struct dirent *ptr;
	char base[1000]; 
	if ((dir=opendir(cate_dir.c_str())) == NULL)
        {
			perror("Open dir error...");
            //exit(1);
        } 
	while ((ptr=readdir(dir)) != NULL)
	{
		if(strcmp(ptr->d_name,".")==0 || strcmp(ptr->d_name,"..")==0)    ///current dir OR parrent dir	
		{
			continue;
		}
		else if	(ptr->d_type == 8)    ///file
		{
			printf("d_name:%s%s\n",cate_dir.c_str(),ptr->d_name);
			//files.push_back(ptr->d_name);
			continue;
		}
		else if(ptr->d_type == 10)    ///link file
		{
			printf("d_name:%s/%s\n",cate_dir.c_str(),ptr->d_name);
			continue;
		}
		else if(ptr->d_type == 4)    ///dir
		{
			files.push_back(ptr->d_name);
			printf("d_name:%s%s\n",cate_dir.c_str(),ptr->d_name);
		}
	}
	closedir(dir); 
	return files;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值