文件的创建:
可以使用 `std::fstream` 中的 `open()` 函数来创建新的文件,如果文件已经存在,则该函数会将其打开。
#include <fstream>
int main() {
std::ofstream outfile("example.txt"); //创建文件
outfile.close(); //关闭文件
return 0;
}
</fstream>
文件的删除:
可以使用 `std::remove()` 函数来删除文件。
#include <cstdio>
int main() {
if (std::remove("example.txt") == 0) {
std::puts("文件删除成功!");
} else {
std::puts("文件删除失败!");
}
return 0;
}
</cstdio>
文件的复制:
可以使用 `std::filesystem` 中的 `copy()` 函数来复制文件。
#include <filesystem>
namespace fs = std::filesystem;
int main() {
fs::copy("from.txt", "to.txt");
return 0;
}
</filesystem>
文件属性的获取与修改:
可以使用 `std::filesystem` 中的函数来获取文件的属性,并用 `std::filesystem::permissions()` 函数来修改文件权限。
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
int main() {
fs::path filePath { "example.txt" };
// 获取文件的属性
fs::file_status status { fs::status(filePath) };
std::cout << "file size: " << fs::file_size(filePath) << " bytes
";
std::cout << "permissions: " << ((status.permissions() & fs::perms::owner_write) !=
fs::perms::none ? "writable" : "not writable") << '\n';
// 修改文件权限
fs::permissions(filePath, fs::perms::owner_write);
return 0;
}
</filesystem></iostream>
目录的遍历:
可以使用 `std::filesystem::directory_iterator` 来遍历指定目录中的所有文件和子目录。
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
int main() {
fs::path currentPath{ fs::current_path() };
for (auto& entry : fs::directory_iterator(currentPath)) {
std::cout << entry.path() << '\n';
}
return 0;
}
</filesystem></iostream>
请注意,为了避免操作系统相关的问题,建议在处理文件和目录路径时使用 C++17 的`std::filesystem` 命名空间。