【问题标题】:Clear data inside all files in C++在 C++ 中清除所有文件中的数据
【发布时间】:2017-09-14 01:38:26
【问题描述】:

大家好,我正在使用 C++ 编程。我希望清除当前目录中所有文件中的所有数据。谁能告诉我获取所有文件的命令吗?

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

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

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

【问题讨论】:

    标签: c++ visual-studio file fstream


    【解决方案1】:

    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);
    }
    

    【讨论】:

    • 感谢队友,但这根本不起作用..i.imgur.com/li6azNC.png
    • 命名空间名称是不允许的。
    • 你需要一个 C++17 编译器,而不是你需要在 linux 的 dirent.h 头文件中使用 opendir()/readdir() 函数
    猜你喜欢
    • 2013-06-06
    • 2017-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多