c++ 获取特定目录下的文件夹个数

项目需求,需要计算某一项操作前后文件夹的个数增加了多少,实现了一下。

主要用到了#include<io.h>库,十分给力。

//计算文件夹的个数
int OERSProductLayer::visit(string path, int layer)
{
	struct _finddata_t   filefind;
	string  curr = path + "\\*.*";
	int   done = 0, i, handle;
	int filenum = 0;
	if ((handle = _findfirst(curr.c_str(), &filefind)) == -1)return -1;
	while (!(done = _findnext(handle, &filefind)))
	{
		//printf("%s\n", filefind.name);
		if (!strcmp(filefind.name, "..")){
			continue;
		}
		//for (i = 0; i < layer; i++)cout << "     ";
		if ((_A_SUBDIR == filefind.attrib)) //是目录
		{
			//printf("----------%s\n", filefind.name);
			//cout << filefind.name << "(dir)" << endl;
			curr = path + "\\" + filefind.name;
			filenum += 1;
		}
		else//不是目录,是文件     
		{
			//cout << path + "\\" + filefind.name << endl;
		}
	}
	_findclose(handle);
	return filenum;
}

调用的时候是在一个切片程序中的,具体如下:

bool OERSProductLayer::gdal2tiles(QString pszSrcFile, QString outFpath)
{
	//调cmd切片
	//pszSrcFile 输入的tif路径 outFpath 输出切片路径
	vector<string> files1;
	int filenum1 = visit(outFpath.toStdString(), 1);

	string wL = "H:\\gdal2tiles.py  -p geodetic -r near " + pszSrcFile.toStdString() + "  " + outFpath.toStdString();
	system(wL.c_str());

	int filenum2 = visit(outFpath.toStdString(), 1);
	int theMaxTilesNum = filenum2 - filenum1;
	cout << theMaxTilesNum;

	return true;
}

总的main函数为:

OERSProductLayer *ssw_HDFfile = new OERSProductLayer;
QString outpath = "H:\\12.tif";
QString path = "H:\\";
ssw_HDFfile->gdal2tiles(outpath, path);
这样可以很好的计算出文件夹增加的数量。


另外在网上找到获取目录下所有文件的函数,可以为参考来:

void OERSProductLayer::getFiles(string path, vector<string>& files)
{
	//文件句柄  
	long   hFile = 0;
	//文件信息  
	struct _finddata_t fileinfo;
	string p;
	if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1)
	{
		do
		{
			//如果是目录,迭代之  
			//如果不是,加入列表  
			if ((fileinfo.attrib &  _A_SUBDIR))
			{
				if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
					getFiles(p.assign(path).append("\\").append(fileinfo.name), files);
			}
			else
			{
				files.push_back(p.assign(path).append("\\").append(fileinfo.name));
			}
		} while (_findnext(hFile, &fileinfo) == 0);
		_findclose(hFile);
	}
}

参考:

https://zhidao.baidu.com/question/1387026905208964700.html

https://www.cnblogs.com/fnlingnzb-learner/p/6424563.html


猜你喜欢

转载自blog.csdn.net/baidu_31933141/article/details/80607650