C++下遍历文件夹

编写程序遍历文件夹及其子文件夹下所有文件,并输出到标准输出流或者文件流。

1. 先考虑在单层目录下,遍历所有文件。以C:\WINDOWS为例:

用到数据结构_finddata_t,文件信息结构体的指针。

struct _finddata_t{    unsigned attrib;     //文件属性    time_t time_create;  //文件创建时间    time_t time_access;  //文件上一次访问时间    time_t time_write;   //文件上一次修改时间    _fsize_t size;  //文件字节数    char name[_MAX_FNAME]; //文件名}; 

文件属性是无符号整数,取值为相应的宏:_A_ARCH(存档),_A_SUBDIR(文件夹),_A_HIDDEN(隐藏),_A_SYSTEM(系统),_A_NORMAL(正常),_A_RDONLY(只读)。容易看出,通过这个结构体,我们可以得到关于该文件的很多信息。结合以下函数,我们可以将文件信息存储到这个结构体中:

//按FileName命名规则匹配当前目录第一个文件_findfirst(_In_ const char * FileName, _Out_ struct _finddata64i32_t * _FindData);  //按FileName命名规则匹配当前目录下一个文件_findnext(_In_ intptr_t _FindHandle, _Out_ struct _finddata64i32_t * _FindData); //关闭_findfirst返回的文件句柄_findclose(_In_ intptr_t _FindHandle);

_findfirst 函数返回的是匹配到文件的句柄,数据类型为long。遍历过程可以指定文件类型,这通过FileName的赋值来实现,例如要遍历C:\WINDOWS下的所有.exe文件

bool transfer(string fileName = "C:\\Windows\\*.exe", int exeNum = 0)
{
_finddata_t fileInfo;
long handle = _findfirst(fileName.c_str(), &fileInfo);

if (handle == -1L)
{
cerr << "failed to transfer files" << endl;
return false;
}

do
{
exeNum ++;
cout << fileInfo.name <<endl;
} while (_findnext(handle, &fileInfo) == 0);
cout << " .exe files‘ number: " << exeNum << endl;

return true;
}

bool transfer(string fileName = "C:\\Windows\\*.exe", int exeNum = 0){    _finddata_t fileInfo;    long handle = _findfirst(fileName.c_str(), &fileInfo);

if (handle == -1L)    {        cerr << "failed to transfer files" << endl;        return false;    }

do     {        exeNum ++;        cout << fileInfo.name <<endl;    } while (_findnext(handle, &fileInfo) == 0);    cout << " .exe files‘ number:  " << exeNum << endl;

return true;}

2. 遍历文件夹及其子文件夹下所有文件。操作系统中文件夹目录是树状结构,使用深度搜索策略遍历所有文件。用到_A_SUBDIR属性,可运行程序如下:

void dfsFolder(string folderPath, ofstream &fout)
{
_finddata_t FileInfo;
string strfind = folderPath + "\\*";
long Handle = _findfirst(strfind.c_str(), &FileInfo);

if (Handle == -1L)
{
cerr << "can not match the folder path" << endl;
exit(-1);
}
do{
//判断是否有子目录
if (FileInfo.attrib & _A_SUBDIR)
{
//这个语句很重要
if( (strcmp(FileInfo.name,".") != 0 ) &&(strcmp(FileInfo.name,"..") != 0))
{
string newPath = folderPath + "\\" + FileInfo.name;
dfsFolder(newPath, fout);
}
}
else
{
fout << folderPath << "\\" << FileInfo.name << " ";
}
}while (_findnext(Handle, &FileInfo) == 0);

_findclose(Handle);
fout.close();
}

void dfsFolder(string folderPath, ofstream &fout){    _finddata_t FileInfo;    string strfind = folderPath + "\\*";    long Handle = _findfirst(strfind.c_str(), &FileInfo);

if (Handle == -1L)    {        cerr << "can not match the folder path" << endl;        exit(-1);    }    do{        //判断是否有子目录        if (FileInfo.attrib & _A_SUBDIR)            {            //这个语句很重要            if( (strcmp(FileInfo.name,".") != 0 ) &&(strcmp(FileInfo.name,"..") != 0))               {                string newPath = folderPath + "\\" + FileInfo.name;                dfsFolder(newPath, fout);            }        }        else          {            fout << folderPath << "\\" << FileInfo.name  << " ";        }    }while (_findnext(Handle, &FileInfo) == 0);

_findclose(Handle);    fout.close();}

在判断有无子目录的if分支中,由于系统在进入一个子目录时,匹配到的头两个文件(夹)是"."(当前目录),".."(上一层目录)。需要忽略掉这两种情况。当需要对遍历到的文件做处理时,在else分支中添加相应的代码就好

原文地址:https://www.cnblogs.com/byteHuang/p/9534836.html

时间: 2024-08-13 09:28:17

C++下遍历文件夹的相关文章

linux下遍历文件夹---opendir等用法

首先要说肯定是头文件,#include <sys/types.h>   #include <dirent.h> linux下遍历文件夹需要用到以下几个函数,其中有三个是必须的,其它几个是可选的. DIR* opendir(const char * name);   失败返回NULL.成功返回DIR结构体.注意DIR前面没有struct,如果加上编译器会warning struct dirent *readdir(struct DIR* dir);   失败返回NULL. void

windows 下遍历文件夹

1 void reversedir(string srcDir) 2 { 3 struct _finddata_t filefind; 4 string imgName = srcDir + "\\*.*"; 5 int done=0, handle; 6 7 if(( handle =_findfirst(imgName.c_str(), &filefind)) == -1) 8 return; 9 10 while(!(done=_findnext(handle, &

OpenCV实现遍历文件夹下所有文件

OpenCV中有实现遍历文件夹下所有文件的类Directory,它里面包括3个成员函数:(1).GetListFiles:遍历指定文件夹下的所有文件,不包括指定文件夹内的文件夹:(2).GetListFolders:遍历指定文件夹下的所有文件夹,不包括指定文件夹下的文件:(3).GetListFilesR:遍历指定文件夹下的所有文件,包括指定文件夹内的文件夹. 若要使用Directory类,则需包含contrib.hpp头文件,此类的实现在contrib模块. 下面为测试代码: cv::Dire

Java遍历文件夹下所有文件并替换指定字符串

应用场景:比如有一个深层次的文件目录结构,如:javaAPI 每个文件里面都有相同的内容,而我们要统一修改为其他内容.上千个文件如果一个个修改显得太不明智. import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.PrintWriter; public class Test { /** *

Linux下的C程序,遍历文件夹并统计其中各个类型文件所占百分比

递归遍历一个目录下的所有文件和文件夹,统计各个类型文件所占的百分比 程序代码a.cpp(编译命令:g++ a.cpp -o a) #include <stdio.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <stdlib.h> #include <dirent.h> #include <string.h> stru

C#遍历文件夹(包括子目录)下的所有文件

前提现在一个分区下建立bb.txt文件. 1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Windows.Forms; 9 using System.IO; 10 11 name

Java遍历文件夹下的所以文件

利用Java递归遍历文件夹下的所以文件,然后对文件进行其他的操作.如:对文件进行重命名,对某一类文件进行重编码.可以对某一工程下的全部.java文件进行转码成utf-8等 代码如下,这里只对文件进行重命名操作 1 package com.zhang.test; 2 3 import java.io.File; 4 5 public class getfilepath { 6 7 public static void main(String[] args) { 8 getDirectory(new

python遍历文件夹下的文件

在读文件的时候往往需要遍历文件夹,python的os.path包含了很多文件.文件夹操作的方法.下面列出: os.path.abspath(path) #返回绝对路径 os.path.basename(path) #返回文件名 os.path.commonprefix(list) #返回多个路径中,所有path共有的最长的路径. os.path.dirname(path) #返回文件路径 os.path.exists(path)  #路径存在则返回True,路径损坏返回False os.path

PHP遍历文件夹下的文件和获取到input name的值

<?php$dir = dirname(__FILE__); //要遍历的目录名字 ->当前文件所在的文件夹//$dir='D:\PHP\wamp\www\admin\hosts\admin'; //PHP遍历文件夹下所有文件 $handle=opendir($dir."."); $arr = array();while($file=readdir($handle)){  if(is_file($file)){ if ($file != "."&