C++目录遍历:使用第三方库boost.filesystem等

遍历目录下文件/子目录(C/C++) 一、第三方库 Poco Poco库的功能很强大,且支持跨系统,其中DirectoryIterator类具有强大的文件操作功能,下面就是个简单的遍历目录下文件的代码示例: #include #include #include #include "Poco/DirectoryIterator.h" using Poco::DirectoryIterator; #include "Poco 阅读详情

1. opencv 目录文件遍历

注释:2014 0814 这个代码是基于java的,Java使用托管代码进行目录管理,C++就不那么跨平台了.

原文链接:http://blog.csdn.net/zxlstudio/article/details/10100345

在做图像处理的时候,可能进行一个文件夹的所有文件的遍历。

使用c 的文件夹遍历方式,代码太难理解,而且如果在windows中使用还需要使用wchar_t宽字符。

opencv本身就有目录遍历的类库,非常方便,我以前还一直傻傻的使用c的方式进行遍历。

示例代码:非常简单的操作

#include "iostream"  
#include "stdio.h"   
#include "opencv\cv.h"  
#include "opencv\highgui.h"  
#include <opencv2\opencv.hpp>  
  
using namespace std;  
using namespace cv;  
  
int main(int argc, char* argv[])  
{  
    string dir_path = "C:/Users/zxl/Desktop/XOXO/New folder/";  
    Directory dir;  
    vector<string> fileNames = dir.GetListFiles(dir_path, "*.jpg", false);  
  
    for(int i=0; i < fileNames.size(); i++)  
    {  
        string fileName = fileNames[i];  
        string fileFullName = dir_path + fileName;  
        cout<<"file name:"<<fileName<<endl;  
        cout<<"file paht:"<<fileFullName<<endl;  
    }  

    system("pause");  
    return 0;  
} 

效果:



2. 用C++遍历目录:

http://blog.chinaunix.net/uid-24462747-id-2980901.html


3..使用boost::filesystem实现目录遍历

http://blog.sina.com.cn/s/blog_48d4cf2d0100mx4o.html

下面的代码实现了深度优先和广度优先两种遍历方式,可以指定最大遍历深度,可以指定结果中是否包含子文件夹
======================================================================
#include <string>
#include <vector>
#include <deque>
#include <utility>
#include<boost/filesystem/operations.hpp>
#include<boost/filesystem/path.hpp>

class file_tool
{
public:

 
   enum traverse_order_t
    {
        DEPTH_FIRST = 1,
        BREADTH_FIRST =2,   
    };

    enum { UNLIMITED_DEPTH =-1};

    static bool get_sub_files(conststd::string& path,std::vector<std::string>&files, int max_depth = UNLIMITED_DEPTH, bool include_sub_dirs =false, traverse_order_t order = BREADTH_FIRST)
    {
        using namespace std;
        namespace fs =boost::filesystem;
        typedefstd::pair<string,int> path_and_depth_t;      
       deque<path_and_depth_t> qu;
        {
           fs::path root(path);
            if(!fs::exists(root) ||!fs::is_directory(root))
           {
               return false;
           }
            if(max_depth <= 0 &&max_depth != UNLIMITED_DEPTH)
           {
               return true;          
           }          
           fs::directory_iteratorend_iter;
            for(fs::directory_iteratorfile_itr(root); file_itr != end_iter; ++file_itr)
           {
              qu.push_back(path_and_depth_t(fs::system_complete(*file_itr).native_directory_string(),1));                                 
           }          
       }       
        while (!qu.empty())
        {
           path_and_depth_t path_and_depth = (order == DEPTH_FIRST) ?qu.back() : qu.front();
           string& file_str(path_and_depth.first);
            int depth= path_and_depth.second;
            if (order== DEPTH_FIRST)
           {
               qu.pop_back();
           }
            else
           {
               qu.pop_front();
           }
           fs::path file(file_str);
            if(fs::exists(file))
           {
               if(fs::is_directory(file))
               {
                   if (include_sub_dirs)
                   {
                      files.push_back(file_str);                     
                   }
                   if (depth <max_depth || max_depth == UNLIMITED_DEPTH)
                   {
                       intnext_depth = depth + 1;
                      fs::directory_iteratorend_iter;
                       for(fs::directory_iteratorfile_itr(file); file_itr != end_iter; ++file_itr)
                      {
                         qu.push_back(path_and_depth_t(fs::system_complete(*file_itr).native_directory_string(),next_depth));                                
                      }
                   }
               }
               else
               {
                  files.push_back(file_str);                  
               }
           }          
        }
        return true;
    }

};


4.使用boost filesystem递归遍历文件夹

原文链接:http://www.th7.cn/Program/cp/2012/02/21/60128.shtml

编译环境vc 9

#ifndef SCANALLFILES_H
#define SCANALLFILES_H
#include "boost/filesystem/operations.hpp"
#include "boost/filesystem/path.hpp"
#include <iostream>
using namespace std;

class ScanAllFiles{
public:
    static const vector<string>& scanFiles(const string&,vector<string>&); //方法一,自己写递归,用filesystem里的directory_iterator
    static const vector<string>& scanFilesUseRecursive(const string&,vector<string>&); //方法二,直接用boost的filesystem里的recursive_directory_iterator
};
//方法一,自己写递归
const vector<string>& ScanAllFiles::scanFiles(const string& rootPath,vector<string>& container=*(new vector<string>())){
    namespace fs = boost::filesystem;
    fs::path fullpath (rootPath, fs::native);
    vector<string> &ret = container;
   
    if(!fs::exists(fullpath)){return ret;}
    fs::directory_iterator end_iter;  /**无参构造函数是最后那个iterator的value 摘抄如下
*If the end of the directory elements is reached, the iterator becomes equal to the end iterator value. The constructor directory_iterator() with no arguments always constructs an end iterator object, which is the only legitimate iterator to be used for the end condition. The result of operator* on an end iterator is not defined. For any other iterator value a const directory_entry& is returned. The result ofoperator-> on an end iterator is not defined. For any other iterator value a const directory_entry* is returned.
*
**/
    for(fs::directory_iterator iter(fullpath);iter!=end_iter;iter++){
        try{
            if (fs::is_directory( *iter ) ){
                std::cout<<*iter << "is dir.whose parent path is " << iter->path().branch_path() << std::endl;
                ret.push_back(iter->path().string()); //递归前push_back进去一个
                ScanAllFiles::scanFiles(iter->path().string(),ret);//递归,把vector也传进去
            }else{
                ret.push_back(iter->path().string());
                std::cout << *iter << " is a file" << std::endl;
            }
        } catch ( const std::exception & ex ){
            std::cerr << ex.what() << std::endl;
            continue;
        }
    }
    return ret;
}
//方法二,直接用boost的filesystem里的recursive_directory_iterator
const vector<string>& ScanAllFiles::scanFilesUseRecursive(const string& rootPath,vector<string>& container=*(new vector<string>())){
    namespace fs = boost::filesystem;
    fs::path fullpath (rootPath, fs::native);
    vector<string> &ret = container;
   
    if(!fs::exists(fullpath)){return ret;}
    fs::recursive_directory_iterator end_iter;
    for(fs::recursive_directory_iterator iter(fullpath);iter!=end_iter;iter++){
        try{
            if (fs::is_directory( *iter ) ){
                std::cout<<*iter << "is dir" << std::endl;
                ret.push_back(iter->path().string());
                //ScanAllFiles::scanFiles(iter->path().string(),ret);
            }else{
                ret.push_back(iter->path().string());
                std::cout << *iter << " is a file" << std::endl;
            }
        } catch ( const std::exception & ex ){
            std::cerr << ex.what() << std::endl;
            continue;
        }
    }
    return ret;
}
#endif


5.我的代码:......

bool CCvMLP::loadFileList(const boost::filesystem::path &base_dir, const std::string &extension,
    std::vector<std::string> &FileList)
{
    if (!boost::filesystem::exists (base_dir) && !boost::filesystem::is_directory (base_dir))
        return true;

    boost::filesystem::directory_iterator it(base_dir);

    for (;
        it != boost::filesystem::directory_iterator ();
        ++it)
    {
        if (boost::filesystem::is_directory (it->status ()))
        {
            std::stringstream ss;
            ss << it->path ();
            loadFileList (it->path (), extension, FileList);
        }
        if (boost::filesystem::is_regular_file (it->status ()) && boost::filesystem::extension (it->path ()) == extension)
        {
            std::string Path;
            Path =base_dir.string();
            Path.append("/");
            Path.append(it->path().filename().string());  
            FileList.push_back (Path);
        }
    }
    return (true);
}


6.我的代码-第二个版本

int loadFilelist(std::string  folder, const std::string  extension, std::vector<std::string>  &Filelist)
{
	//std::vector<std::string>  Filelist(0);
	Filelist.resize(0);
	Traverse(folder.c_str(), extension.c_str(), Filelist);
	//for ( auto ptr = Filelist.begin(); ptr != Filelist.end(); ++ptr )
	//{
	//}
	if (Filelist.size() > 0){
		for (int i = 0; i < Filelist.size(); ++i){
			std::string T = Filelist[i];
			std::string tF(folder);
			tF.append(T);
			Filelist[i] = tF;
		}
	}

	//return int32_t(1);
	return (1);
}

void Traverse( const char *pszPath, const char *extension, std::vector<std::string>& vctFileName )
{
	char szFind[MAX_PATH] = { 0 };
	char szFile[MAX_PATH] = { 0 };

	WIN32_FIND_DATAA FindFileData;

	//strcpy(szFind, pszPath);
	//strcpy_s(szFind, strlen(pszPath), pszPath);
	strcpy_s(szFind, 200, pszPath);
	//strcat(szFind, "//*.bmp");
	if (0){
		strcat_s(szFind, sizeof(szFind), "//*.bmp");
	}
	else{
		strcat_s(szFind, sizeof(szFind), "//*");
		strcat_s(szFind, sizeof(szFind), extension);
	}

	HANDLE  hFind = ::FindFirstFileA(szFind, &FindFileData);
	if (INVALID_HANDLE_VALUE == hFind)	{
		return;
	}

	while (TRUE)	{
		if (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)	{
			//if(FindFileData.cFileName[0]!='.')  
			//{  
			//    strcpy(szFile,lpPath);  
			//    strcat(szFile,"//");  
			//    strcat(szFile,FindFileData.cFileName);  
			//    Traverse(szFile);  
			//}  
		}
		else{
			//cout<<FindFileData.cFileName<<endl;  
			vctFileName.push_back(FindFileData.cFileName);
		}
		if (!FindNextFileA(hFind, &FindFileData)){
			break;
		}
	}
	FindClose(hFind);
}

#include <windows.h>


C++实现跨平台递归删除目录:基于Boost.Filesystem的健壮rmdir工具 文件系统操作是软件开发中的基础任务,其核心在于对目录和文件进行安全、高效的管理。递归删除目录是其中的典型需求,它要求深度遍历目录树,并遵循“先子项后父项”的删除原则,以确保操作的系统兼容性与数据安全性。在C++工程实践中,Boost.Filesystem库提供了强大的跨平台文件系统操作能力,其path类、目录迭代器和状态查询函数构成了实现健壮删除逻辑的基石。通过封装自定义的rmdir函数,开发者不仅能深入理解递归算法与错误处理机制,还能为安装程序、清理工具等应用场景提供标准化的解决方案。本文聚焦于利用Boo 阅读详情

相关推荐

boost::filesystem::directory_iterator实现目录遍历的测试程序

boost::filesystem::directory_iterator实现目录遍历的测试程序实现功能C++实现代码 实现功能 boost::filesystem::directory_iterator实现目录遍历的测试程序 C++实现代码 #include <boost/filesystem.hpp> #include <boost/foreach.hpp> #include <boost/config.hpp> namespace fs = boost::files

希望我的博客,能帮上你解决学习中工作中所遇到的问题 1380

C++ 三方库Boost_filesystem总结

C++ 三方库Boost_filesystem总结

qq_44681788的博客 1873

Silvaco TCAD实战 | SiC MOSFET工艺仿真与关键参数DOE分析

本文详细介绍了使用Silvaco TCAD进行SiC MOSFET工艺仿真与关键参数DOE分析的实战方法。通过外延生长建模、离子注入工艺调试等步骤,结合DOE分析优化器件性能,帮助工程师在设计阶段预判电学特性,提升产品可靠性。文章还分享了网格划分、界面态建模等实用技巧,助力实现从仿真到产品的闭环验证。

weixin_30235225的博客 513

BOOST 之filesystem, path

目录[-] 使用 boost::filesystem 的第一个程序 清单 1. 用于确定某个文件的类型是否为 Directory 的代码 了解 Boost path 对象 清单 2. 创建 Boost path 对象的方法 清单 3. 使用本机格式初始化 path 清单 4. 使用可移植格式初始化 path path 成员函数概述 清单 5. 使用 path::iterator(begin 和 end 接口) 清单 6. 路径字符串的串联 错误处理 清单 7. Boost 中的错误处理

buknow的博客 3460

用Python玩转农业大数据:从Landsat遥感影像到作物产量预测实战教程

本文详细介绍了如何利用Python处理Landsat遥感影像数据,并结合土壤信息构建作物产量预测模型。从环境搭建、数据预处理到模型训练与可视化,提供了一套完整的农业大数据分析实战方案,帮助读者掌握遥感影像处理和机器学习在精准农业中的应用。

weixin_30832143的博客 408

ROS2+PYTHON VENV虚拟环境配置方法

ROS2+PYTHON VENV配置方法本篇针对的是python。

下雨夏云的博客 564

boost::filesystem库使用入门

以下知识点转自:点击打开原文链接 今天拿起手要用C++写个小工具,从指定的目录递归遍历文件,然后做一下处理。又翻了一下boost的filesystem库。小结一下,希望能加深印象,免得下次又要查看文档。 1. path对象就是一个跨平台的路径对象。有许多方法访问路径的各个部分,也用它的iterator迭代路径中的各个部分;      path构造目录结构的时候使用“/”运算符,非常直

明天,你又将身在何方…… 4621

从智能手机到汽车电子:聊聊IPC-9702/9704A标准如何帮我们搞定不同场景下的PCB可靠性设计

本文探讨了IPC-9702/9704A标准在智能手机和汽车电子等不同场景下的PCB可靠性设计应用。通过分析消费电子、汽车电子和工业设备中的应力特征,详细解读了IPC标准在应变识别和测试方法论中的核心价值,并提供了具体的轻量化设计策略和全生命周期验证方案,帮助工程师提升PCB的长期可靠性。

weixin_30693683的博客 284

fs::directory_iterator

类来遍历目录中的所有内容。例如,下面的代码将遍历目录。如果你只想遍历目录中的文件,可以使用。

sun007700的专栏 593

别再手动找触点了!EPLAN线圈触点映像的3种显示方式与F键/Ctrl+B快捷键实战

本文详细解析EPLAN线圈触点映像的3种显示方式与F键/Ctrl+B快捷键实战技巧,帮助电气设计工程师提升图纸操作效率。通过精简编号、路径栏显示和元件旁可视化三种模式的应用场景对比,结合快捷键肌肉记忆训练法,实现触点快速定位与管理,大幅减少手动查找时间。

weixin_42522964的博客 486

华为OD机试 - 不含101的数(Python/JS/C/C++ 双机位C卷 100分)

本专栏收录于《华为OD机试真题(Python/JS/C/C++)》。刷的越多,抽中的概率越大,私信哪吒,备注华为OD,加入华为OD刷题交流群,每一题都有详细的答题思路、详细的代码注释、3个测试用例、为什么这道题采用XX算法、XX算法的适用场景,发现新题目,随时更新。小明在学习二进制时,发现了一类不含101的数,也就是:现在给定一个正整数区间,请问这个区间内包含了多少个不含101的数?输入的唯一一行包含两个正整数。输出的唯一一行包含一个整数,表示在区间内一共有几个不含101的数。8 1668 → “1000”

学Java,找哪吒 1257

【C++】boost::filesystem遍历文件目录

boost::filesystem是Boost C++ Libraries中的一个模块,主要作用是处理文件(Files)和目录(Directories)。 在c++中使用boost库遍历文件目录。 demo // demo.cpp #include <iostream> #include <boost/filesystem.hpp> #include <boost/algorithm/string/classification.hpp> #include <bo

sinat_38685124的博客 4435

基于 InceptionNeXt 模块增强的 YOLOv8 模型:针对多尺度目标检测的改进与实现

modules.py。

know_F0727的博客 216

Boost filesystem

本文详细介绍了Boost.Filesystem库的核心功能和使用方法。该库提供跨平台的文件系统操作接口,主要包括:路径判断函数(如exists()、is_directory())、路径获取与操作(如current_path()、parent_path())、文件操作(remove()、copy_file())、目录管理(create_directories())以及信息查询(space()、last_write_time())等功能。文章还展示了路径简化方法canonical()和目录遍历技巧,包括递归遍历

人无远虑,必有近忧 4340

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

C++文件与目录操作:高效管理存储系统

本文介绍了C++文件与目录操作的核心技术,包括文件路径处理、创建/读写文件、目录操作和权限管理。通过标准库和Boost.Filesystem库,开发者可以高效实现文件系统管理功能。文章提供了完整代码示例,展示如何创建/删除文件目录、遍历文件系统以及设置文件权限,帮助读者掌握C++中处理存储系统的关键技能。

编程世界如山海,探索不止。 3万+

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

C++使用boost::filesystem实现遍历文件夹内文件

C++17中使用 boost::filesystem 实现遍历文件夹的方法

m0_43605481的博客 9069

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

C++使用BOOST操作文件、目录

开始使用 在BOOST库出现之前,C++对于文件和目录的操作,大都借助于UNIX提供的底层文件和目录接口,从使用角度来看,这些底层的操作不够友好。BOOST中filesystem库是一种可移植的文件系统操作库,可以跨平台的操作目录、文件等,在不失性能的情况下,提供了友好的操作方法。本文主要介绍在UNIX环境中,boost::filesystem的常用操作方法。假设你已经安装好了bo...

dizi9750的博客 1248

Boost::filesystem directory_iterator迭代器

最方便的一个功能是遍历path里的所有内容。directory_iterator。      path p;      directory_iterator(p)就是迭代器的起点,无参数的directory_iterator()就是迭代器的终点。           获取目录下的所有文件名 #include    namespace fs = boost::filesys

pilqc2009的专栏 1万+

boost::filesystem的使用

介绍 filesystem库是一个可移植的文件系统操作库,它在底层做了大量的工作,使用POSIX标准表示文件系统的路径,使C++具有了类似脚本语言的功能,可以跨平台操作目录、文件,写出通用的脚本程序。 1.path的构造函数可以接受C字符串和string,也可以是一个指定首末迭代器字符串序列区间。 2.filesystem提供了一系列的文件名(或目录)检查函数。 3.有丰富的函数用于获取文...

A_L_A_N 5055

std::filesystem 使用笔记

C++17的filesystem库为文件和目录操作提供了标准化的解决方案。该库包含在<filesystem>头文件中,主要功能包括:路径操作(判断、获取、简化)、文件管理(创建/删除/复制/移动)、属性查询(空间、修改时间)以及目录遍历。其中,directory_iterator支持递归遍历子目录,path类支持路径拼接和相对路径转换。关键特性包括跨平台兼容性、异常安全处理和丰富的路径操作方法,极大简化了文件系统相关编程任务。典型应用场景包括批量文件处理、路径规范化检查和磁盘空间监控等。

人无远虑,必有近忧 2565

超详细的Boost使用

Boost是 C++ 的一个强大的开源库,提供了很多功能,涵盖了各种领域,包括数据结构、算法、内存管理、并发编程、日期时间处理等。Boost的设计目标是增强 C++ 的功能,提供可移植性,且大部分库在 C++ 标准库中已经得到了采纳。

ITOfDragon的博客 1112

使用boost中的filesystem类库遍历某个目录所有的文件

#include #include 使用boost中的filesystem类库遍历某个目录所有的文件int GetAllFileOfPath(const string strPath){namespace fs = boost::filesystem; // 得到配置文件夹. if ( strPath.size()  {  return 0; } fs::path full_path( f

roger007的专栏 8418

C++遍历文件夹,使用boost filesystem递归遍历文件夹

编译环境vc 9 #ifndef SCANALLFILES_H#define SCANALLFILES_H#include "boost/filesystem/operations.hpp"#include "boost/filesystem/path.hpp"#include using namespace std;class ScanAllFiles{public: stati

870

boost filesystem 遍历目录

void PrintAllFile(fs::path full_path) { if (fs::exists(full_path)) { fs::directory_iterator item_begin(full_path); fs::directory_iterator item_end; for (; item_begin !...

苦逼码农 2647
上一篇: 科学存储数据格式-HDF5
下一篇: VS2012 编译 boost1.53/ boost1.49
wishchin
博客等级 码龄16年 1370粉丝 381原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值