C++ 文件系统笔记

                     

贡献者: addis

#include <iostream>
#include <filesystem>
#include <fstream>

namespace fs = std::filesystem;

int main() {
    // Define a path for a new directory and a file inside it
    fs::path dirPath = "example_dir";
    fs::path filePath = dirPath / "example_file.txt";

    // 1. Create a directory
    if (!fs::exists(dirPath)) {
        fs::create_directory(dirPath);
        std::cout << "Directory created: " << dirPath << std::endl;
    }

    // 2. Create a file and write to it
    std::ofstream file(filePath);
    if (file.is_open()) {
        file << "This is a sample file.\\n";
        file.close();
        std::cout << "File created and written to: " << filePath << std::endl;
    } else {
        std::cerr << "Failed to create the file!" << std::endl;
    }

    // 3. Check file properties
    if (fs::exists(filePath)) {
        std::cout << "File exists: " << filePath << std::endl;
        std::cout << "File size: " << fs::file_size(filePath)
            << " bytes" << std::endl;
    }

    // 4. Copy the file to a new location
    fs::path copiedFilePath = dirPath / "copied_file.txt";
    fs::copy(filePath, copiedFilePath);
    std::cout << "File copied to: " << copiedFilePath << std::endl;

    // 5. Rename the copied file
    fs::path renamedFilePath = dirPath / "renamed_file.txt";
    fs::rename(copiedFilePath, renamedFilePath);
    std::cout << "File renamed to: " << renamedFilePath << std::endl;

    // 6. Delete the original file
    fs::remove(filePath);
    std::cout << "Original file deleted: " << filePath << std::endl;

    // 7. Remove the directory and all contents
    fs::remove_all(dirPath);
    std::cout << "Directory and all contents removed: "
        << dirPath << std::endl;

    return 0;
}


致读者: 小时百科一直以来坚持所有内容免费无广告,这导致我们处于严重的亏损状态。 长此以往很可能会最终导致我们不得不选择大量广告以及内容付费等。 因此,我们请求广大读者热心打赏 ,使网站得以健康发展。 如果看到这条信息的每位读者能慷慨打赏 20 元,我们一周就能脱离亏损, 并在接下来的一年里向所有读者继续免费提供优质内容。 但遗憾的是只有不到 1% 的读者愿意捐款, 他们的付出帮助了 99% 的读者免费获取知识, 我们在此表示感谢。

                     

友情链接: 超理论坛 | ©小时科技 保留一切权利