巧用ifstream判断文件是否存在

  最近在写手写数字的识别软件,训练样例数量巨大而且数字个数不唯一,有可能在中途粘出一部分做测试样例。因此写下面的脚本来获取文件名,之后丢到训练函数里。

 #include <algorithm>
#include <iostream>
#include <iomanip>
#include <cstring>
#include <climits>
#include <complex>
#include <fstream>
#include <cassert>
#include <cstdio>
#include <bitset>
#include <vector>
#include <deque>
#include <queue>
#include <stack>
#include <ctime>
#include <set>
#include <map>
#include <cmath> #include <opencv.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/ml/ml.hpp>
#include <opencv2/core/core.hpp>
#include <opencv_modules.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp> #define cvQueryHistValue_1D( hist, idx0 ) \
((float)cvGetReal1D( (hist)->bins, (idx0))) using namespace std;
using namespace cv; const string rootDir("./sample/");
const string jpg(".jpg");
const string dirNames[] = {
rootDir + "0/", rootDir + "1/", rootDir + "2/",
rootDir + "3/", rootDir + "4/", rootDir + "5/",
rootDir + "6/", rootDir + "7/", rootDir + "8/",
rootDir + "9/"
}; inline void i2s(string& str, int i, int len = ) {
stringstream ss;
ss << setw(len) << setfill('') << i;
str = ss.str();
} void train(string fileName) { } void getFile(string dirName, int num) {
static int sum = ;
string tmp;
string fileName;
string snum;
stringstream ss;
int cur = ; tmp.clear();
ss << num; ss >> snum;
ifstream fileRead;
for (; ; cur++) {
i2s(tmp, cur);
fileName = dirNames[num] + snum + "_" + tmp + jpg;
if (cur == ) cout << "start file name : " << fileName << endl;
fileRead.open(fileName);
if (!fileRead) {
cout << "end file name : " << fileName << endl;
break;
}
fileRead.close();
train(fileName);
}
sum += cur - ;
cout << "current number of samples : " << sum << endl << endl;
} int main() {
int i = ;
for (int i = ; i != ; i++) {
getFile(dirNames[i], i);
}
return ;
}

巧用ifstream判断文件是否存在

上一篇:Python之集合(set)


下一篇:BaseActivity的抽取