今後、役に立ちそうなプログラムを作ったら、ライブラリとして整備して、ちまちまと公開していくことにします。
今回、作成したfile_viewerクラスは、あるフォルダににあるファイルを自動で探索し、
一覧を取得するクラスで、簡易的なエクスプローラのような機能を提供します。
(基本的な使い方)
- コンストラクタでルートパスを設定
- directories/filesメソッドでディレクトリ/ファイル一覧を取得
- exploreメソッドでサブディレクトリに移動&自動探索
[拡張子 zip は無効化されているため、表示できません]
ライブラリをビルドして、パスを設定すれば、コピペで動きます。
【file_viewer.h】
► スポイラーを表示
#pragma once
#include
#include
#include
namespace a5ua
{
namespace file_view
{
/**
* あるパスをルートとして、階層的にディレクトリを探索し、ファイル一覧を取得するためのクラス
*/
class file_viewer
{
public:
/**
* コンストラクタ
*
* @param root_path ルートとなるパス。このパスより上の階層を探索することはできない
*/
explicit file_viewer(const std::wstring &root_path);
/**
* デストラクタ
*/
~file_viewer();
/**
* サブディレクトリを探索する
*
* @param sub_directory_name 探索するディレクトリ名
*
* @return 成功したかどうかの真偽値(falseが返った場合、viewerの状態は変化しない)
*/
bool explore(const std::wstring &sub_directory_name);
/**
* 現在のディレクトリビューを更新する
* 現在のディレクトリがすでに削除されている場合、上の階層に自動的に移動する
*
* @return 更新が成功したかどうかの真偽値
* @retval true 正常終了
* @retval false ルートディレクトリが削除されている
*/
bool refresh();
/**
* 現在のディレクトリビューのパスを返す
*
* @return カレントディレクトリのパスを表す文字列
*/
const std::wstring &path() const;
/**
* サブディレクトリ名のリストを返す
*
* @return 現在のディレクトリが直近に持つサブディレクトリ名の文字列リスト
*/
const std::vector &directories() const;
/**
* このディレクトリが持つファイル名のリストを返す
*
* @return 現在のディレクトリが直近に持つファイル名の文字列リスト
*/
const std::vector &files() const;
private:
file_viewer(const file_viewer &);
file_viewer &operator=(const file_viewer &);
class impl;
impl *m_impl; ///
#include
#include
#include
#include
#include
#include
// コンテナの中身を指定文字列で区切って出力
template
void print(Container &c, const E *delim)
{
std::copy(c.cbegin(), c.cend(), std::ostream_iterator(std::wcout, delim));
}
// メニューを表示
void menu(const a5ua::file_view::file_viewer &viewer)
{
// カレントパス
std::wcout ";
}
// ディレクトリ名の入力受付・更新処理
bool update(a5ua::file_view::file_viewer &viewer)
{
std::wstring input;
// EOF入力で終了
if (!std::getline(std::wcin, input)) {
return false;
}
// 空文字の場合は、更新する
if (input.empty()) {
if (!viewer.refresh()) {
std::wcerr << L"ルートディレクトリが削除されました" << std::endl;
return false;
}
return true;
}
// 無効なディレクトリ名が入力された場合、エラーメッセージを表示して継続
if (!viewer.explore(input)) {
std::wcerr << L"ディレクトリが見つかりません" << std::endl;
}
return true;
}
int main()
{
std::wcin.imbue(std::locale("japanese"));
std::wcout.imbue(std::locale("japanese"));
std::wcerr.imbue(std::locale("japanese"));
// カレントディレクトリをルートとする
a5ua::file_view::file_viewer viewer(L".");
// 簡易コマンドラインインタプリタ
do menu(viewer); while (update(viewer));
}