c++怎么判断文件是否存在_C++检查文件或文件夹存在与否的实现

34次阅读
c++kquote>答案:C++中判断文件或目录是否存在可采用多种方法。首选C++17的std::filesystem,提供exists和is_directory函数,跨平台且简洁;若不支持C++17,可在Unix系统使用access()函数,Windows下用GetFileAttributes判断属性;兼容性最强的是fopen尝试打开文件,但仅适用于文件且无法区分目录。应根据项目平台和标准选择合适方式。

c++怎么判断文件是否存在_C++检查文件或文件夹存在与否的实现

在C++中判断文件或文件夹是否存在,有多种实现方式,取决于你使用的标准和平台。以下是几种常用且跨平台或标准支持的方法。

使用 C++17 的 std::filesystem

C++17 引入了 std::filesystem,提供了简洁的接口来检查文件或目录是否存在。

示例代码:

#include <filesystem>
#include <iostream>

namespace fs = std::filesystem;

bool fileExists(const std::string& path) {
    return fs::exists(path);
}

bool isDirectory(const std::string& path) {
    return fs::is_directory(path);
}

int main() {
    std::string filepath = “test.txt”;
    std::string dirpath = “my_folder”;

    if (fileExists(filepath)) {
        std::cout << filepath << ” 存在n”;
    } else {
        std::cout << filepath << ” 不存在n”;
    }

    if (isDirectory(dirpath)) {
        std::cout << dirpath << ” 是一个目录n”;
    }

    return 0;
}

编译时需要启用 C++17:g++ -std=c++17 your_file.cpp -o your_program

立即学习C++免费学习笔记(深入)”;

使用 POSIX 函数 access()(适用于 Linux/Unix)

在类 Unix 系统中,可以使用 access() 函数检查文件是否存在。

示例代码:

#include <unistd.h>
#include <iostream>
#include <string>

bool fileExists(const std::string& path) {
    return access(path.c_str(), F_OK) == 0;
}

注意:access() 在 Windows 上不可靠或不推荐使用,建议仅用于 Unix-like 系统。

c++怎么判断文件是否存在_C++检查文件或文件夹存在与否的实现

文赋Ai论文

专业/高质量智能论文AI生成器-在线快速生成论文初稿

c++怎么判断文件是否存在_C++检查文件或文件夹存在与否的实现37

查看详情 c++怎么判断文件是否存在_C++检查文件或文件夹存在与否的实现

使用 fopen 尝试打开文件

一种兼容性很强的方法是尝试用 fopen 打开文件,如果成功则存在,然后立即关闭。

示例代码:

#include <cstdio>
#include <string>

bool fileExists(const std::string& path) {
    FILE* fp = fopen(path.c_str(), “r”);
    if (fp != nullptr) {
        fclose(fp);
        return true;
    }
    return false;
}

这种方法兼容所有平台,但只适用于文件,不能直接判断目录是否存在。

Windows API 判断文件或文件夹

在 Windows 平台,可使用 GetFileAttributes 函数。

示例代码:

#include <windows.h>
#include <iostream>

bool fileExists(const std::string& path) {
    DWORD attr = GetFileAttributesA(path.c_str());
    return (attr != INVALID_FILE_ATTRIBUTES);
}

bool isDirectory(const std::string& path) {
    DWORD attr = GetFileAttributesA(path.c_str());
    if (attr == INVALID_FILE_ATTRIBUTES) return false;
    return (attr & FILE_ATTRIBUTE_DIRECTORY);
}

此方法适用于 Windows,需链接 kernel32.lib(通常自动包含)。

基本上就这些。如果你使用的是现代 C++,优先选择 std::filesystem;若需兼容老标准或特定平台,可选用对应方法。关键是根据项目环境选择合适方案。

linux word windows access ai unix c++ ios win stream String if include fopen fclose Filesystem const bool int 接口 Namespace windows linux unix Access

text=ZqhQzanResources