Reputation: 75
Hi guys I am programming on C++. I wish to clear all the data inside of all files in the current directory. Can someone tell me the command to get all files?
That is what I am trying but it doesn't work:
ofs.open("*.*", ios::out | ios::trunc);
The problem is: open("*.*",
Upvotes: 0
Views: 152
Reputation: 169
fstream can't open all files of a directory, instead, you can iterate each file.
This example only works on 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()
}
}
}
Older compilers(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);
}
Upvotes: 1