zoukankan      html  css  js  c++  java
  • 用c++读取文件夹中的所有文件名

    //头文件,注意要加stdafx.h和io.h等
    
    #include "stdafx.h"
    #include <io.h>
    #include <vector>
    using namespace std;

    下面这个子函数计算了当前指定path文件夹下的所有文件(包括迭代子文件夹中的文件)

    //获取子文件名的子函数
    //path指向要读取的文件夹路径
    //files是一个字符串向量,存储文件夹内的文件名
    
    void 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);
        }
    }
    //main函数内调用
    
    char * filePath = "D:\wenjian";  //主文件夹路径
        vector<string> files;  //子文件夹容器
        ////获取该路径下的所有文件
        getFiles(filePath, files );

    说到文件路径顺便说一下文件路径的申明一般是char* path 或是  char path[100],也有可能加入<string.h>后的 String path

    如果将新的读出来的files向量中的某一个文件名files[i]加入path,那么字符串的赋值 可以直接用 String本身的构造函数:

    String path(files[i]);

    以下代码未经验证,单纯补充文章完整性

    附上一段《只读取某给定路径下的当前文件夹名》(有两个版本)

  • 相关阅读:
    Class constructor FileManager cannot be invoked without 'new' in undefined (line undefined, column undefined)
    vscode插件
    面试题
    使用NPOI读取word表格里面的图片
    Postgresql安装过程记录
    .net Core 新增Area的步骤
    kendo grid上的模版示例
    unicode与string之间的转换
    使用yarn安装puppeteer失败的解决方案
    abp第一篇《框架的下载与mysql数据库的切换》
  • 原文地址:https://www.cnblogs.com/Daringoo/p/4469187.html
Copyright © 2011-2022 走看看