c++でfilesystemライブラリの使い方は何ですか?

C++17では、ファイルシステム内のファイルやディレクトリを処理するためのクラスや関数のセットが含まれた標準ライブラリが導入されました。このライブラリを使用することで、ファイルやディレクトリの作成、コピー、移動、削除などの様々な操作を簡単に行うことができ、ディレクトリの走査やファイルの属性の取得も可能です。

以下は「庫」の一般的な使い方です:

  1. ディレクトリを作成する:
#include <filesystem>

std::filesystem::create_directory("path/to/directory");
  1. ファイルを作成する。
#include <filesystem>

std::ofstream file("path/to/file.txt");
  1. ファイルをコピーする。
#include <filesystem>

std::filesystem::copy("source_file.txt", "destination_file.txt");
  1. ファイルを移動する:
#include <filesystem>

std::filesystem::rename("source_file.txt", "destination_file.txt");
  1. ファイルやディレクトリを削除する:
#include <filesystem>

std::filesystem::remove("path/to/file_or_directory");
  1. ディレクトリを横断する:
#include <filesystem>

for (const auto& entry : std::filesystem::directory_iterator("path/to/directory")) {
    std::cout << entry.path() << std::endl;
}
  1. ファイルの属性を取得します。
#include <filesystem>

std::filesystem::file_status status = std::filesystem::status("path/to/file.txt");
if (std::filesystem::is_regular_file(status)) {
    std::cout << "Regular file" << std::endl;
}

これらはライブラリ内の一般的な使用法の一部であり、具体的な要件に応じて柔軟に利用できます。注意すべきは、ライブラリ内のクラスや関数の定義がstd::filesystem名前空間内にあることです。

bannerAds