今天尝试在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”丢失了数据。
因此仅需稍作改动即可:
成功!!