Initial Commit

master
Kirigaya Kazuto 2018-06-25 11:16:59 +08:00
commit 4d64652686
3 changed files with 181 additions and 0 deletions

22
FileWrapper.h Normal file
View File

@ -0,0 +1,22 @@
#pragma once
#include <string>
#include <functional>
class DirWalk
{
public:
DirWalk(const std::string& DirName);
~DirWalk();
// noncopyable, nonmovable.
DirWalk(const DirWalk&) = delete;
DirWalk& operator = (const DirWalk&) = delete;
DirWalk(DirWalk&&) = delete;
DirWalk& operator = (DirWalk&&) = delete;
bool isReady() const;
int next(std::string& name, bool& is_dir);
std::string getroot() const;
private:
struct _impl;
_impl* _p;
};

77
FileWrapper_Lin.cpp Normal file
View File

@ -0,0 +1,77 @@
#ifndef _WIN32
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <cstdlib>
struct DirWalk::_impl
{
DIR* dir;
std::string root;
};
DirWalk::DirWalk(const std::string& DirName)
{
std::string realname = DirName;
int sz = realname.size();
if (realname[sz-1] != '/')
{
realname.push_back('/');
}
if ((_p->dir = opendir(realname .c_str())) != NULL)
{
_p->root = realname;
}
else
{
_status = -1;
}
}
DirWalk::~DirWalk()
{
closedir(_p->dir);
delete _p;
}
bool DirWalk::isReady() const
{
return _p->dir != NULL;
}
int DirWalk::next(std:; string& name, bool& is_dir)
{
dirent* file = NULL;
if ((file = readdir(Dir)) != NULL)
{
if (file->d_type == DT_DIR)
{
if (strcmp(file->d_name, ".") != 0 &&
strcmp(file->d_name, "..") != 0)
{
is_dir = true;
name = file->d_name;
return 1;
}
else return next(name, is_dir);
}
else
{
name = file->d_name;
is_dir = false;
return 1;
}
}
else
{
return 0;
}
}
std::string DirWalk::getroot()
{
return _p->root;
}
#endif // End of ifndef _WIN32

82
FileWrapper_Win.cpp Normal file
View File

@ -0,0 +1,82 @@
#ifdef _WIN32
#include "FileWrapper.h"
#include <Windows.h>
struct DirWalk::_impl
{
HANDLE hand;
WIN32_FIND_DATA fnd;
std::string root;
// -1 Not Opened 0 End 1 Ready
int status;
};
DirWalk::DirWalk(const std::string& DirName) : _p(new _impl)
{
std::string realname = DirName;
int sz = realname.size();
if (realname[sz - 1] != '\'')
{
realname.push_back('\\');
}
_p->root = realname;
realname.push_back('*');
_p->hand = FindFirstFile(realname.c_str(), &_p->fnd);
if (_p->hand != INVALID_HANDLE_VALUE)
{
_p->status = 1;
}
else
{
_p->status = -1;
}
}
DirWalk::~DirWalk()
{
if (_p->hand != INVALID_HANDLE_VALUE)
{
FindClose(_p->hand);
}
delete _p;
}
bool DirWalk::isReady() const
{
return _p->status >= 0;
}
std::string DirWalk::getroot() const
{
return _p->root;
}
int DirWalk::next(std::string& name, bool& is_dir)
{
if (_p->status == 1)
{
name = _p->fnd.cFileName;
if (_p->fnd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
is_dir = true;
}
else
{
is_dir = false;
}
// Step down
if (!FindNextFile(_p->hand, &_p->fnd))
{
_p->status = 0;
}
return 1;
}
else
{
return 0;
}
}
#endif // End of _WIN32