C++ 判断文件或者目录是否存在

2021-07-07  本文已影响0人  book_02

1. 说明

  1. 如果编译器支持C++17,则建议使用std::filesystem相关函数
  2. 也可使用stat函数来判断

2. 使用std::filesystem相关函数

#include <filesystem>
    
std::string file_name = "deadman";
if (std::filesystem::exists(file_name)) {
    if (std::filesystem::is_directory(file)) {
        printf("%s is a directory\n", file_name.c_str());
    }
    else if (std::filesystem::is_regular_file(file)) {
        printf("%s is a file\n", file_name.c_str());
    }
    else {
        printf("%s exists\n", file_name.c_str());
    } 
}
else {
    printf("%s does not exist\n", file_name.c_str());
}

3. 使用stat函数

windows平台和linux平台都适用

#include <sys/types.h>
#include <sys/stat.h>

std::string file_name = "deadman";
struct stat info;
if (stat(file_name.c_str(), &info) != 0) {  // does not exist
    printf("cannot access %s\n", file_name.c_str());
}        
else if (info.st_mode & S_IFDIR) {          // directory
    printf("%s is a directory\n", file_name.c_str());
}        
else {
    printf("%s is no directory\n", file_name.c_str());
}  
上一篇下一篇

猜你喜欢

热点阅读