tv_rename/filesystem.hpp
2019-01-03 19:01:43 +01:00

107 lines
2.1 KiB
C++

#ifndef FSLIB_H
#define FSLIB_H
#include <string>
#include <dirent.h>
#include <string.h>
namespace FSLib{
bool exists(const std::string &path);
bool isDirectory(const std::string &path);
std::string canonical(const std::string &path);
bool rename(const std::string &file_a, const std::string &file_b);
class Directory {
public:
Directory(const std::string &path_) : dir_path(path_) {}
Directory() = delete;
Directory(const Directory &d) = default;
Directory(Directory &&d) = default;
class Iterator {
public:
Iterator( const Directory &d_ ) : d(opendir(d_.path())) {
current_entry = readdir(d);
}
Iterator( const Directory &d_, const struct dirent *current_entry_) : d(opendir(d_.path())), current_entry(current_entry_) {}
Iterator() = delete;
Iterator(const Iterator &i) = default;
Iterator(Iterator &&i) = default;
~Iterator() {
closedir(d);
}
std::string operator*() {
return current_entry->d_name;
}
Iterator &operator++() {
if( current_entry == nullptr )
return *this;
current_entry = readdir(d);
if( current_entry != nullptr && (!strcmp(current_entry->d_name, ".") || !strcmp(current_entry->d_name, "..")) )
operator++();
return *this;
}
Iterator operator++(int) {
Iterator ret(*this);
operator++();
return ret;
}
bool operator==(const Iterator &i_other) {
return i_other.current_entry == current_entry;
}
bool operator!=(const Iterator &i_other) {
return i_other.current_entry != current_entry;
}
private:
DIR *d;
const struct dirent *current_entry;
};
using iterator = Iterator;
using const_iterator = Iterator;
iterator begin() {
return Iterator(dir_path);
}
const_iterator begin() const {
return Iterator(dir_path);
}
const_iterator cbegin() const {
return begin();
}
iterator end() {
return Iterator(dir_path, nullptr);
}
const_iterator end() const {
return Iterator(dir_path, nullptr);
}
const_iterator cend() const {
return end();
}
const char *path() const {
return dir_path.c_str();
}
private:
std::string dir_path;
};
} //end FSLib
#endif