温馨提示×

C++ Linux下如何管理文件系统

小樊
72
2025-06-11 18:44:59
栏目: 编程语言

在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

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时,还需要注意错误处理,上面的示例代码为了简洁起见省略了错误处理部分。在实际应用中,你应该检查每个函数的返回值,并适当处理可能发生的错误。

0