tv_rename/filesystem.hpp
2019-02-04 17:39:48 +01:00

145 lines
3.1 KiB
C++

#ifndef FSLIB_H
#define FSLIB_H
#include <string.h>
#include <string>
#ifdef _WIN32
#include <Windows.h>
#else
#include <dirent.h>
#endif
// set apropriate data types for each operating system
#ifdef _WIN32
using string = std::wstring;
using char_t = wchar_t;
#else
using string = std::string;
using char_t = char;
#endif
// windows version stolen from
// http://www.martinbroadhurst.com/list-the-files-in-a-directory-in-c.html
namespace FSLib {
#ifndef GUI
bool exists( const string &path );
string canonical( const string &path );
#endif
bool isDirectory( const string &path );
bool rename( const string &file_a, const string &file_b );
class Directory {
public:
Directory( const string &path_ ) : dir_path( path_ ) {
#ifdef _WIN32
// need to append \\* for windows to search files in directory
dir_path.append( L"\\*" );
#endif
}
Directory() = delete;
Directory( const Directory &d ) = default;
Directory( Directory &&d ) = default;
class Iterator {
public:
#ifdef _WIN32
Iterator( const Directory &d_ ) {
hFind = FindFirstFileW( d_.path(), &data );
if ( hFind != INVALID_HANDLE_VALUE ) {
if ( !wcscmp( data.cFileName, L"." ) ||
!wcscmp( data.cFileName, L".." ) ) {
++( *this );
}
} else {
ended = true;
}
}
// this is definitely not a good way to create the "end" iterator
// but it was the only way I thought of with my limited knowledge of
// windows.h
Iterator( bool ended_ ) : ended( ended_ ) {}
~Iterator() {
if ( hFind )
FindClose( hFind );
}
#else
Iterator( const Directory &d_ ) : d( opendir( d_.path() ) ) {
current_entry = readdir( d );
if ( current_entry != nullptr &&
( !strcmp( current_entry->d_name, "." ) ||
!strcmp( current_entry->d_name, ".." ) ) )
++( *this );
}
Iterator( const Directory &d_, const struct dirent *current_entry_ )
: d( opendir( d_.path() ) ), current_entry( current_entry_ ) {}
~Iterator() {
closedir( d );
}
#endif
Iterator() = delete;
Iterator( const Iterator &i ) = default;
Iterator( Iterator &&i ) = default;
char_t const *operator*() const;
Iterator &operator++();
Iterator operator++( int );
bool operator==( const Iterator &i_other ) const;
bool operator!=( const Iterator &i_other ) const;
private:
#ifndef _WIN32
DIR *d;
const struct dirent *current_entry;
#else
HANDLE hFind;
WIN32_FIND_DATA data;
bool ended{ false };
#endif
};
using iterator = Iterator;
using const_iterator = Iterator;
iterator begin();
const_iterator begin() const;
const_iterator cbegin() const;
iterator end();
const_iterator end() const;
const_iterator cend() const;
const char_t *path() const;
private:
string dir_path;
};
} // namespace FSLib
#endif