清除C 中所有文件中的数据
Clear data inside all files in C++
嗨,我在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);
}
相关文章:
- C++数据文件、数组和计算赋值
- 数据文件的第二行未正确读取
- 在 C++/C 中使用 CURL 发出带有数据文件的 GET HTTP 请求
- 将数据文件读入结构 C++
- 引入流时C++数据文件未正确读取?
- 如何在数据文件中查找和显示内容
- 如何处理错误"E1696命令行错误:无法在Visual Studio 2017中打开元数据文件"mscorlib.dll"?
- 尝试读取数据文件,存储在数组中并打印所有元素,但它不起作用
- 将数据文件读入对象数组时出现问题
- C :数据文件有错误:预期的无限制ID
- C 和 C++:带有错误"Expected unqualified-id"的数据文件
- 如何在C 中读取一系列数据文件
- 从数据文件中读取每2个字节,并在向量中进行比较
- 写入单个大数据文件或多个小文件:哪个更快?
- 在读取数据文件时,如何找到用户字符串输入的字谜?
- 保护外部数据文件免受未经授权的修改
- C 读取数据文件
- C 如何将数据文件读取到结构或向量以及返回结构或向量
- 具有挑战性的数据文件格式,需要将其读取为包含类对象的数组的VAR
- C 中的Google单元测试:如何编写持久数据文件