在Linux下使用C++管理文件系统,你可以使用C++标准库中的<filesystem>头文件(C++17及以后版本支持),或者使用POSIX API。下面是一些基本操作的示例:
<filesystem> 头文件(推荐)<filesystem> 是C++17引入的,提供了一种面向对象的方式来处理文件和目录。
#include <filesystem>
namespace fs = std::filesystem;
void createDirectory(const std::string& path) {
if (!fs::exists(path)) {
fs::create_directory(path);
}
}
void removeFile(const std::string& path) {
if (fs::exists(path)) {
fs::remove(path);
}
}
void removeDirectory(const std::string& path) {
if (fs::exists(path) && fs::is_directory(path)) {
fs::remove_all(path);
}
}
bool fileExists(const std::string& path) {
return fs::exists(path);
}
bool isDirectory(const std::string& path) {
return fs::is_directory(path);
}
void listDirectory(const std::string& path) {
if (fs::exists(path) && fs::is_directory(path)) {
for (const auto& entry : fs::directory_iterator(path)) {
std::cout << entry.path() << std::endl;
}
}
}
POSIX API是Linux系统上的一组标准API,用于文件和目录操作。
#include <sys/stat.h>
#include <sys/types.h>
void createDirectory(const char* path) {
mkdir(path, 0755);
}
#include <unistd.h>
void removeFile(const char* path) {
unlink(path);
}
void removeDirectory(const char* path) {
rmdir(path);
}
#include <sys/stat.h>
bool fileExists(const char* path) {
struct stat buffer;
return (stat(path, &buffer) == 0);
}
bool isDirectory(const char* path) {
struct stat buffer;
return (stat(path, &buffer) == 0 && S_ISDIR(buffer.st_mode));
}
#include <dirent.h>
void listDirectory(const char* path) {
DIR* dir = opendir(path);
if (dir != nullptr) {
struct dirent* entry;
while ((entry = readdir(dir)) != nullptr) {
std::cout << entry->d_name << std::endl;
}
closedir(dir);
}
}
请注意,POSIX API在非POSIX兼容的系统(如Windows)上可能不可用。如果你需要编写跨平台的代码,建议使用<filesystem>头文件。在使用这些API时,还需要注意错误处理,上面的示例代码为了简洁起见省略了错误处理部分。在实际应用中,你应该检查每个函数的返回值,并适当处理可能发生的错误。