c++ 判断文件是否存在

创建日期: 2023-05-27 16:30 | 作者: 风波 | 浏览次数: 15 | 分类: C++

来源:https://blog.csdn.net/xfxf996/article/details/106235087/

分别使用 std::ifstreamfopenaccessstat 测试文件是否存在。

#include <sys/stat.h> // stat()
#include <unistd.h> // access()
#include <iostream>
#include <fstream>

int main(int argc, char *argv[]) {
    if (argc < 2) {
        std::cout << "Usage: " << argv[0] << " filepath" << std::endl;
        return 1;
    }
    const std::string filepath = argv[1];

    // use ifstream testing
    std::ifstream f(filepath.c_str());
    auto func = "ifstream";
    if(f.good()) {
        std::cout << func << ": file exists: " << filepath << std::endl;
    } else {
        std::cout << func << ": file not exists: " << filepath << std::endl;
    }

    // use fopen
    func = "fopen";
    FILE *fp = fopen(filepath.c_str(), "r");
    if(fp) {
        std::cout << func << ": file exists: " << filepath << std::endl;
        fclose(fp);
    } else {
        std::cout << func << ": file not exists: " << filepath << std::endl;
    }

    // use access
    func = "access";
    if(access(filepath.c_str(), F_OK) != -1) {
        std::cout << func << ": file exists: " << filepath << std::endl;
    } else {
        std::cout << func << ": file not exists: " << filepath << std::endl;
    }

    // use stat
    func = "stat";
    struct stat buffer;
    if(stat (filepath.c_str(), &buffer) == 0) {
        std::cout << func << ": file exists: " << filepath << std::endl;
    } else {
        std::cout << func << ": file not exists: " << filepath << std::endl;
    }

    return 0;
}
15 浏览
9 爬虫
0 评论