清除C+中所有文件中的数据+; 嗨,我是用C++编程的。我希望清除当前目录中所有文件中的所有数据。有人能告诉我获取所有文件的命令吗

清除C+中所有文件中的数据+; 嗨,我是用C++编程的。我希望清除当前目录中所有文件中的所有数据。有人能告诉我获取所有文件的命令吗,c++,visual-studio,file,fstream,C++,Visual Studio,File,Fstream,这就是我正在尝试的,但它不起作用: ofs.open("*.*", ios::out | ios::trunc); 问题是:open(“*.*”,fstream无法打开一个目录的所有文件,相反,您可以迭代每个文件。 此示例仅适用于C++17 #include <string> #include <iostream> #include <filesystem> #include <fstream> //nam

这就是我正在尝试的,但它不起作用:

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()
            }
        }
    }
#包括
#包括
#包括
#包括
//命名空间fs=std::experimental::filesystem;//用于visual studio
命名空间fs=std:::文件系统;
int main()
{
std::string path=“路径到目录”;
for(auto&p:fs::directory\u迭代器(path)){
if(fs::is_regular_file(p)){
std::fstream fstr;
fstr.open(p.path().c_str(),std::ios::out | std::ios::trunc);
//做点什么
fstr.close()
}
}
}
较旧的编译器(Windows):

#包括
#包括
#包括
std::wstring path=L“路径到目录”;
路径+=L“\\*”;
WIN32_查找_数据;
处理高频风;
if((hFind=FindFirstFile(path.c_str(),&data))!=INVALID_HANDLE_值){
做{
if(data.dwFileAttributes和文件属性存档){
std::fstream fstr;
fstr.open(data.cFileName,std::ios::out | std::ios::trunc);
//做点什么
fstr.close();
}
}while(FindNextFile(hFind,&data)!=0);
FindClose(hFind);
}

谢谢mate,但这根本不起作用..不允许使用Namespacename。您需要一个C++17编译器,而需要linux的dirent.h头中的opendir()/readdir()函数
#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);
}