x64下vs2013 C++遍历目录下所有文件使用_findnext()调试时中断

来源:互联网 发布:怎样在淘宝上卖东西 编辑:程序博客网 时间:2024/06/08 07:18

今天尝试在VS2013 win32控制台下写一个手写数字的机器学习程序,其中需要遍历某目录下的所有.txt文件,在网上查了大量方法,主流是这样的


#include <opencv2/opencv.hpp>#include <stdio.h>#include <io.h>#include <string>using namespace std;void getFiles(string path, vector<string>& files, string postfix){//文件句柄    long   hFile = 0;//文件信息    struct _finddata_t fileinfo;string p;if ((hFile = _findfirst(p.assign(path).append(postfix).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, postfix);}else{files.push_back(p.assign(fileinfo.name));}} while (_findnext(hFile, &fileinfo) == 0);_findclose(hFile);}}


但调试运行时会出现的问题,如下



显然,上图为地址访问出错,

其实是因为_findfirst()返回类型为intptr_t而非long型,从“intptr_t”转换到“long”丢失了数据。


因此仅需稍作改动即可:


成功!



顺便提醒一下,在使用这个函数的时候,有一个后缀参数,例如希望访问到所有的 .txt
文件,那么在使用的时候,可以把后缀参数设置为:  *txt

这个也有输入的path有关系,如果path不是以\\结尾,那么后缀参数记得加上,当然修改这个函数也行。

2 0
原创粉丝点击