LoginSignup
1
2

More than 5 years have passed since last update.

filesystem(std::tr2::sys)を使ってディレクトリ内のファイルを別ディレクトリにコピーする

Last updated at Posted at 2017-01-23

環境

Microsoft Visual Studio Professional 2012

参考

ディレクトリ内にある全ファイル/ディレクトリを列挙する
<filesystem>

filesystem

<fstream> より多機能で使いやすい。
boost::filesystem のようなインターフェイスになっている。

#include <filesystem>

void copyDirectory(const std::tr2::sys::path& srcDirectory,
                   const std::tr2::sys::path& destDirectory)
{
    // 対象のディレクトリが無ければ作成
    if (std::tr2::sys::exists(destDirectory) == false)
    {
        if (std::tr2::sys::create_directories(destDirectory) == false)
        {
            // 失敗
            assert(false);
            return;
        }
    }

    // コピー対象のディレクトリを確認
    for (std::tr2::sys::directory_iterator it(srcDirectory);
         it != std::tr2::sys::directory_iterator(); ++it)
    {
        std::tr2::sys::path target              = *it;
        target = srcDirectory / target;
        const std::tr2::sys::path next          = target.filename();
        const std::tr2::sys::path nextDestFile  = destDirectory / next;

        // ディレクトリ?
        if (std::tr2::sys::is_directory(target))
        {
            // 再帰呼び出し
            copyDirectory
            (
                srcDirectory / next,
                nextDestFile
            );
        }        
        // ファイル
        else
        {
            std::tr2::sys::copy_file
            (
                target,
                nextDestFile,
                std::tr2::sys::copy_option::overwrite_if_exists
            );
        }

    }
}

int main()
{
    try
    {
        const std::tr2::sys::path src = "src";
        const std::tr2::sys::path dest = "dest";
        copyDirectory(src, dest);
    }
    catch (...)
    {
        assert(false);
    }

    return 0;
}
1
2
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2