文章目录
1、C++ 遍历某个文件夹下所有文件的方法步骤
#include<iostream>
#include<string>
#include<io.h>
#include<cstdio>
#include<cstdlib>
#include<cstring>
using namespace std;
void fileSearch(string path)
{
long hFile = 0;
/*
_finddata_t 存储文件各种信息的结构体,<io.h>;
*/
struct _finddata_t fileInfo;
string pathName;
/*
\\* 表示符合的所有文件;
没有找到即文件夹为空,退出;
assign 表示把 pathName清空并置为path;
append 表示在末尾加上字符串;
c_str 返回一个const char* 的临时指针;
_findfirst
搜索与指定的文件名称匹配的第一个实例,若成功则返回第一个实例的句柄,否则返回-1L;
函数原型:long _findfirst( char *filespec, struct _finddata_t *fileinfo );
*/
if ( ( hFile = _findfirst(pathName.assign(path).append("\\*").c_str(), &fileInfo) ) == -1)
return ;
do {
cout << path+"\\"+fileInfo.name << endl;
/*
文件夹下有 . 和 .. 目录,不能进入搜索;
_A_SUBDIR 表示文件夹属性;
*/
if( strcmp(fileInfo.name,"..") && strcmp(fileInfo.name,".") && fileInfo.attrib==_A_SUBDIR )
fileSearch(path+"\\"+fileInfo.name);
} while ( _findnext(hFile, &fileInfo) == 0 );
/*
_findnext 搜索与_findfirst函数提供的文件名称匹配的下一个实例,若成功则返回0,否则返回-1 ;
_findclose 结束查找;
*/
_findclose(hFile);
return ;
}
int main()
{
string path="E:\\Git";
fileSearch(path);
system("pause");
return 0;
}
转载自:https://www.jb51.net/article/180238.htm
2、C++ 遍历文件夹下的所有文件
数据分多个文件存储,读取数据就需要对多个文件进行操作。首先就需要定位到文件的名字,之后再对文件进行相应的读写操作。多次涉及多文件的读写操作,现将这个实现总结一下,方便自己和他人使用。具体代码如下:
#include "stdafx.h"
#include <stdio.h>
#include<iostream>
#include<vector>
#include <Windows.h>
#include <fstream>
#include <iterator>
#include <string>
using namespace std;
#define MAX_PATH 1024 //最长路径长度
/*----------------------------
* 功能 : 递归遍历文件夹,找到其中包含的所有文件
*----------------------------
* 函数 : find
* 访问 : public
*
* 参数 : lpPath [in] 需遍历的文件夹目录
* 参数 : fileList [in] 以文件名称的形式存储遍历后的文件
*/
void find(char* lpPath,std::vector<const std::string> &fileList)
{
char szFind[MAX_PATH];
WIN32_FIND_DATA FindFileData;
strcpy(szFind,lpPath);
strcat(szFind,"\\*.*");
HANDLE hFind=::FindFirstFile(szFind,&FindFileData);
if(INVALID_HANDLE_VALUE == hFind) return;
while(true)
{
if(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
if(FindFileData.cFileName[0]!='.')
{
char szFile[MAX_PATH];
strcpy(szFile,lpPath);
strcat(szFile,"\\");
strcat(szFile,(char* )(FindFileData.cFileName));
find(szFile,fileList);
}
}
else
{
//std::cout << FindFileData.cFileName << std::endl;
fileList.push_back(FindFileData.cFileName);
}
if(!FindNextFile(hFind,&FindFileData)) break;
}
FindClose(hFind);
}
int main()
{
std::vector<const std::string> fileList;//定义一个存放结果文件名称的链表
//遍历一次结果的所有文件,获取文件名列表
find("XXXX具体文件夹目录",fileList);//之后可对文件列表中的文件进行相应的操作
//输出文件夹下所有文件的名称
for(int i = 0; i < fileList.size(); i++)
{
cout << fileList[i] << endl;
}
cout << "文件数目:" << fileList.size() << endl;
return 0;
}
转载自:https://www.jb51.net/article/120289.htm
3、Python 与 C++ 遍历文件夹下的所有图片实现代码
虽然本文说的是遍历图片,但是遍历其他文件也是可以的。
在进行图像处理的时候,大部分时候只需要处理单张图片。但是一旦把图像处理和机器学习相结合,或者做一些稍大一些的任务的时候,常常需要处理好多图片。而这里面,一个最基本的问题就是如何遍历这些图片。
用 OpenCV 做过人脸识别的人应该知道,那个项目中并没有进行图片的遍历,而是用了一种辅助方案,生成了一个包含所有图片路径的文件 at.txt,然后通过这个路径来读取所有图片。而且这个辅助文件不仅包含了图片的路径,还包含了图片对应的标签。所以在进行训练的时候直接通过这个辅助文件来读取训练用的图片和标签。
其实如果去看看教程,会发现这个 at.txt 的生成是通过 Python 代码来实现。所以今天就来看一下如何用 C++ 来实现文件夹下所有图片的遍历。
当然在此之前还是先给出 Python 遍历的代码,以备后用。
1.Python 遍历
在之前的数独项目中,进行图像处理的时候用到了遍历文件夹下所有的图片。主要是利用 glob 模块。glob 是 python 自己带的一个文件操作相关模块,内容不多,可以用它查找符合自己目的的文件。
# encoding: UTF-8
import glob as gb
import cv2
#Returns a list of all folders with participant numbers
img_path = gb.glob("numbers\\*.jpg")
for path in img_path:
img = cv2.imread(path)
cv2.imshow('img',img)
cv2.waitKey(1000)
2.C++ 遍历
1)opencv 自带函数 glob () 遍历
OpenCV 自带一个函数 glob () 可以遍历文件,如果用这个函数的话,遍历文件也是非常简单的。这个函数非常强大,人脸识别的时候用这个函数应该会比用 at.txt 更加方便。一个参考示例如下。
#include<opencv2\opencv.hpp>
#include<iostream>
using namespace std;
using namespace cv;
vector<Mat> read_images_in_folder(cv::String pattern);
int main()
{
cv::String pattern = "G:/temp_picture/*.jpg";
vector<Mat> images = read_images_in_folder(pattern);
return 0;
}
vector<Mat> read_images_in_folder(cv::String pattern)
{
vector<cv::String> fn;
glob(pattern, fn, false);
vector<Mat> images;
size_t count = fn.size(); //number of png files in images folder
for (size_t i = 0; i < count; i++)
{
images.push_back(imread(fn[i]));
imshow("img", imread(fn[i]));
waitKey(1000);
}
return images;
}
需要注意的是,这里的路径和模式都用的是 cv::String。
2)自己写一个遍历文件夹的函数
在 windows 下,没有 dirent.h 可用,但是可以根据 windows.h 自己写一个遍历函数。这就有点像是上面的 glob 的原理和实现了。
#include<opencv2\opencv.hpp>
#include<iostream>
#include <windows.h> // for windows systems
using namespace std;
using namespace cv;
void read_files(std::vector<string> &filepaths,std::vector<string> &filenames, const string &directory);
int main()
{
string folder = "G:/temp_picture/";
vector<string> filepaths,filenames;
read_files(filepaths,filenames, folder);
for (size_t i = 0; i < filepaths.size(); ++i)
{
//Mat src = imread(filepaths[i]);
Mat src = imread(folder + filenames[i]);
if (!src.data)
cerr << "Problem loading image!!!" << endl;
imshow(filenames[i], src);
waitKey(1000);
}
return 0;
}
void read_files(std::vector<string> &filepaths, std::vector<string> &filenames, const string &directory)
{
HANDLE dir;
WIN32_FIND_DATA file_data;
if ((dir = FindFirstFile((directory + "/*").c_str(), &file_data)) == INVALID_HANDLE_VALUE)
return; /* No files found */
do {
const string file_name = file_data.cFileName;
const string file_path = directory + "/" + file_name;
const bool is_directory = (file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
if (file_name[0] == '.')
continue;
if (is_directory)
continue;
filepaths.push_back(file_path);
filenames.push_back(file_name);
} while (FindNextFile(dir, &file_data));
FindClose(dir);
}
3)基于 Boost
如果电脑上配置了 boost 库,用 boost 库来实现这一功能也是比较简洁的。为了用这个我还专门完全编译了 Boost。
然而只用到了 filesystem。
#include <boost/filesystem.hpp>
#include<iostream>
#include<opencv2\opencv.hpp>
using namespace cv;
using namespace std;
using namespace boost::filesystem;
void readFilenamesBoost(vector<string> &filenames, const string &folder);
int main()
{
string folder = "G:/temp_picture/";
vector<string> filenames;
readFilenamesBoost(filenames, folder);
for (size_t i = 0; i < filenames.size(); ++i)
{
Mat src = imread(folder + filenames[i]);
if (!src.data)
cerr << "Problem loading image!!!" << endl;
imshow("img", src);
waitKey(1000);
}
return 0;
}
void readFilenamesBoost(vector<string> &filenames, const string &folder)
{
path directory(folder);
directory_iterator itr(directory), end_itr;
string current_file = itr->path().string();
for (; itr != end_itr; ++itr)
{
if (is_regular_file(itr->path()))
{
string filename = itr->path().filename().string(); // returns just filename
filenames.push_back(filename);
}
}
}
转载自:https://www.jb51.net/article/115156.htm
4、C++ 遍历文件夹获取文件列表
本文实例类似遍历一个文件夹然后获得该文件夹下的文件列表,可以随意切换文件目录,本来是用在我们小组写的简易 ftp 服务器上的一个给客户端显示的一个小插件,总之单拿出来应该没啥含量,调用了 windows 的一些 API。
实例代码:
#include<iostream>
#include<stdlib.h>
#include<windows.h>
#include<fstream>
#include<stdio.h>
#include<vector>
#include<string>
#pragma comment (lib, "winmm.lib")
using namespace std;
void MainMenu()
{
printf("请选择操作\n");
printf("1.显示当前文件夹的所有文件\n");
printf("2.返回上一级\n");
printf("3.进入文件夹\n");
printf("4.进入指定文件夹\n");
printf("5.退出\n");
}
void ShowFileList(string filename)
{
WIN32_FIND_DATAA p;
vector<string> filelist;
HANDLE h = FindFirstFileA(filename.c_str(), &p);
filelist.push_back(p.cFileName);
while (FindNextFileA(h, &p))
{
filelist.push_back(p.cFileName);
if (filelist.back() == "." || filelist.back() == "..")
{
filelist.pop_back();
}
}
for (int i = 0; i < filelist.size(); i++)
{
cout << filelist[i] << endl;
}
}
void ShowLastFileList(string & filepath)
{
string filepath2 = filepath;
string tmp = "../";
tmp += filepath2;
filepath = tmp;
ShowFileList(tmp);
}
void ShowSelectFileList(string filepath)
{
string yourchoose;
cin >> yourchoose;
yourchoose += '/';
string filepath2 = filepath;
yourchoose += filepath2;
ShowFileList(yourchoose);
}
void case4(string filepath)
{
string filename;
cin >> filename;
filename += '/';
filename += filepath;
ShowFileList(filename);
}
int main()
{
string filepath;
filepath = "*.*";
string filePath = filepath;
while (1)
{
system("CLS");
MainMenu();
int n;
cin >> n;
switch (n)
{
case 1:
system("CLS");
ShowFileList(filePath);
system("pause");
break;
case 2:
system("CLS");
ShowLastFileList(filePath);
system("pause");
break;
case 3:
system("CLS");
ShowSelectFileList(filePath);
system("pause");
break;
case 4:
system("CLS");
case4(filepath);
system("pause");
break;
case 5:
exit(0);
break;
default:
break;
}
}
return 0;
}
转载自:https://www.jb51.net/article/83994.htm
5、C++ 遍历文件夹下文件的方法
本文实例讲述了 C++ 遍历文件夹下文件的方法。
#include <windows.h>
#include <stdio.h>
#include <string.h>
#define LEN 1024
// 深度优先递归遍历目录中所有的文件
BOOL DirectoryList(LPCSTR Path)
{
WIN32_FIND_DATA FindData;
HANDLE hError;
int FileCount = 0;
char FilePathName[LEN];
// 构造路径
char FullPathName[LEN];
strcpy(FilePathName, Path);
strcat(FilePathName, "\\*.*");
hError = FindFirstFile(FilePathName, &FindData);
if (hError == INVALID_HANDLE_VALUE)
{
printf("搜索失败!");
return 0;
}
while(::FindNextFile(hError, &FindData))
{
// 过虑.和..
if (strcmp(FindData.cFileName, ".") == 0
|| strcmp(FindData.cFileName, "..") == 0 )
{
continue;
}
// 构造完整路径
wsprintf(FullPathName, "%s\\%s", Path,FindData.cFileName);
FileCount++;
// 输出本级的文件
printf("\n%d %s ", FileCount, FullPathName);
if (FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
printf("<Dir>");
DirectoryList(FullPathName);
}
}
return 0;
}
void main()
{
DirectoryList("D:eclipse-J2EE");
}
转载自:https://www.jb51.net/article/69531.htm
6、C++ 遍历指定文件夹~相应操作
在平时开发中,时常需要遍历指定文件夹目录下的所有文件,在这里总结一下代码。
下面这段代码就是递归遍历指定目录,把遍历出来文件信息保存到 vector 向量里面:
bool FileTra(CString &strDir,vector<CString> &file)
{
if (strDir.IsEmpty()) //如果目录是空的,就退出当前遍历
{
return false;
}
CFileFind filefind;
bool bFound = filefind.FindFile(strDir + _T("\\*"), 0);
while (bFound)
{
bFound = filefind.FindNextFile();
if (filefind.GetFileName() =="."|| filefind.GetFileName() =="..") //跳过隐藏文件
continue;
SetFileAttributes(filefind.GetFilePath(), FILE_ATTRIBUTE_NORMAL);
if (filefind.IsDirectory())
{
FileTra(filefind.GetFilePath(),file);
}
else
{
/*获取文件的各种信息*/
//CString m_strFileAbsolutePath;
//tempFile.m_strFileAbsolutePath=filefind.GetFilePath(); //获取文件绝对路径
CString m_strFileName;
tempFile.m_strFileName=filefind.GetFileName(); //获取文件名
file.push_back(m_strFileName);
}
}
}
除了获取信息,也可以做别的操作,如递归遍历删除指定文件夹,这个也是比较常用的,代码如下:
总体流程还是没什么变化的,主要就是遍历指定目录,然后做相应操作即可。
//遍历删除指定目录下所有文件夹以及文件
void DeleteDirectory(CString strDir)
{
if(strDir.IsEmpty())
{
RemoveDirectory(strDir);
return;
}
//首先删除文件及子文件夹
CFileFind ff;
BOOL bFound = ff.FindFile(strDir+ _T("\\*"),0);
while(bFound)
{
bFound = ff.FindNextFile();
if(ff.GetFileName()== _T(".")||ff.GetFileName()== _T(".."))
continue;
//去掉文件(夹)只读等属性
SetFileAttributes(ff.GetFilePath(),FILE_ATTRIBUTE_NORMAL);
if(ff.IsDirectory())
{
//递归删除子文件夹
DeleteDirectory(ff.GetFilePath());
RemoveDirectory(ff.GetFilePath());
}
else
{
DeleteFile(ff.GetFilePath()); //删除文件
}
}
ff.Close();
//如果有需要连这个文件夹都删除,可以把这一句注释去掉
//RemoveDirectory(strDir);
}
转载自:https://blog.youkuaiyun.com/xuzhiwangray/article/details/53508161
7.1、OpenCV 利用 Directory 类实现文件夹遍历(只适用于 2.x 版本的 opencv)
https://blog.youkuaiyun.com/weixin_42142612/article/details/82229420
7.2 c++ 遍历文件夹下的所有文件
https://blog.youkuaiyun.com/weixin_42142612/article/details/82285398?utm_medium=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase
说明
本文主要是搜索过程中对所找资料的一个整合与转载备份,以备查找方便,均已标明转载地址。