温馨提示×

c++怎么用ofstream清空文件夹

c++
小亿
102
2024-02-23 09:23:27
栏目: 编程语言

在C++中,可以使用ofstream打开文件并使用truncate模式清空文件内容。但是,ofstream无法直接清空整个文件夹。

要清空文件夹,可以使用系统命令或者通过C++代码循环删除文件夹内的文件。以下是使用C++代码循环删除文件夹内的文件的示例:

#include <iostream>
#include <filesystem>

namespace fs = std::filesystem;

void clearFolder(const fs::path& folderPath) {
    for (const auto& entry : fs::directory_iterator(folderPath)) {
        fs::remove_all(entry.path());
    }
}

int main() {
    fs::path folderPath = "path_to_folder";
    clearFolder(folderPath);
    
    return 0;
}

请确保在使用此代码之前备份文件夹中的重要文件,因为这将删除文件夹中的所有文件。

0