清除C 中所有文件中的数据

Clear data inside all files in C++

本文关键字:数据 文件 清除      更新时间:2023-10-16

嗨,我在C 上编程。我希望清除当前目录中所有文件中的所有数据。有人可以告诉我命令获取所有文件吗?

那是我正在尝试的东西,但它行不通:

ofs.open("*.*", ios::out | ios::trunc);

问题是:open("*.*",

fstream无法打开目录的所有文件,而是可以迭代每个文件。
此示例仅适用于C 17

    #include <string>
    #include <iostream>
    #include <filesystem>
    #include <fstream>
    //namespace fs = std::experimental::filesystem; //for visual studio
    namespace fs = std:::filesystem;
    int main()
    {
        std::string path = "path_to_directory";
        for (auto & p : fs::directory_iterator(path)) {
            if (fs::is_regular_file(p)){
                std::fstream fstr;
                fstr.open(p.path().c_str(), std::ios::out | std::ios::trunc);
                //do something
                fstr.close()
            }
        }
    }

旧编译器(Windows):

#include <Windows.h>
#include <string>
#include <fstream>

std::wstring path = L"path_to_directory";
path += L"\*";
WIN32_FIND_DATA data;
HANDLE hFind;
if ((hFind = FindFirstFile(path.c_str(), &data)) != INVALID_HANDLE_VALUE) {
    do {
        if (data.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE) {
            std::fstream fstr;
            fstr.open(data.cFileName, std::ios::out | std::ios::trunc);
            //do something
            fstr.close();
        }
    } while (FindNextFile(hFind, &data) != 0);
    FindClose(hFind);
}