C++实现Linux和Windows下遍历指定目录下的文件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lhanchao/article/details/53576311

一、Linux下遍历方法

方法非常简单,这里不多说了,可以直接看代码
#include <dirent.h>//遍历系统指定目录下文件要包含的头文件
#include <iostream>
using namespace std;

int main()
{
    DIR* dir = opendir("/home/hanchao/picture");//打开指定目录
    dirent* p = NULL;//定义遍历指针
    while((p = readdir(dir)) != NULL)//开始逐个遍历
    {
        //这里需要注意,linux平台下一个目录中有"."和".."隐藏文件,需要过滤掉
        if(p->d_name[0] != '.')//d_name是一个char数组,存放当前遍历到的文件名
        {
            string name = "/home/hanchao/picture/" + string(p->d_name);
            cout<<name<<endl;
        }
    }
    closedir(dir);//关闭指定目录
}
这里需要注意,由于p->d_name存放的是文件名,所以也可以通过像strstr(p->d_name,".jpg")等来判断,遍历指定类型的文件。
文件夹中:
运行结果:

二、Windows下遍历指定目录下所有文件

同样,直接看代码吧。
#include <io.h>//所需头文件
#include <iostream>
#include <string>

using namespace std;

void getAllFileNames(const string& folder_path)
{
	_finddata_t file;
	long flag;
	string filename = folder_path + "\\*.jpg";//遍历制定文件夹内的jpg文件
	if ((flag = _findfirst(filename.c_str(), &file)) == -1)//目录内找不到文件
	{
		cout << "There is no such type file" << endl;
	}
	else
	{
		//通过前面的_findfirst找到第一个文件
		string name = folder_path + "\\" + file.name;//file.name存放的是遍历得到的文件名
		cout << name << endl;
		//依次寻找以后的文件
		while (_findnext(flag, &file) == 0)
		{
			string name = string(folder_path + "\\" + string(file.name));
			cout << name << endl;
		}
	}
	_findclose(flag);
}

int main()
{
	getAllFileNames("test");//test是制定的目录
}
这里在Windows下寻找所有文件也会有“.”和".."文件,如果要遍历目录下的所有文件,则需要过滤这两个,过滤方法同Linux方法。
test原目录下文件:

运行结果:




猜你喜欢

转载自blog.csdn.net/lhanchao/article/details/53576311