C++のboost::filesystemでファイルやディレクトリを操作する方法。
ファイルのコピー
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>
try {
boost::filesystem::path src("C:\\sample\\src.txt");
boost::filesystem::path dst("C:\\sample\\dst.txt");
boost::filesystem::copy_file(src, dst);
} catch (std::exception& e) {
std::cout << e.what() << std::endl;
}
ファイルの削除
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>
boost::filesystem::path src("C:\\sample\\src.txt");
if (boost::filesystem::remove(src)) {
std::cout << "ok" << std::endl; //削除した
}
ファイル名の変更
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>
boost::filesystem::path src("C:\\sample\\src.txt");
boost::filesystem::path dst("C:\\sample\\dst.txt");
try{
boost::filesystem::rename(src, dst);
} catch (std::exception& e) {
std::cout << e.what() << std::endl;
}
ディレクトリの作成
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>
boost::filesystem::path dir("C:\\sample\\test");
if (boost::filesystem::create_directory(dir)) {
std::cout << "ok" << std::endl; //ディレクトリの作成に成功した
}
ディレクトリの削除(ファイルの削除と同じ)
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>
boost::filesystem::path dir("C:\\sample\\test");
if (boost::filesystem::remove(dir)) {
std::cout << "ok" << std::endl; //削除した
}
※ディレクトリが空でない時は削除に失敗する。次の「ディレクトリの内容の取得」でディレクトリを空にしてから削除すること。
ディレクトリの内容の取得
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>
boost::filesystem::path dir("C:\\sample");
boost::filesystem::directory_iterator end;
for (boost::filesystem::directory_iterator p(dir); p != end; ++p) {
std::cout << p->leaf() << std::endl; //ファイル名
std::cout << p->string() << std::endl; //フルパス
if (boost::filesystem::is_directory(*p)) { //ディレクトリの時
std::cout << "<DIR>" << std::endl;
}
}
フルパスからファイル名とパス名を取得する
#include <boost/filesystem/path.hpp>
boost::filesystem::path f("C:\\sample\\src.txt");
std::cout << f.leaf() << std::endl; //=> src.txt
std::cout << f.branch_path() << std::endl; //=> C:\sample