如何检查文件是否是C ++中的常规文件?

问题描述 投票:5回答:6

如果文件是常规文件(并且不是目录,管道等),我如何签入C ++?我需要一个函数isFile()。

DIR *dp;
struct dirent *dirp;

while ((dirp = readdir(dp)) != NULL) {
if ( isFile(dirp)) {
     cout << "IS A FILE!" << endl;
i++;
}

我已经尝试将dirp-> d_type与(unsigned char)0x8进行比较,但它似乎无法通过不同的系统进行移植。

c++ filesystems dirent.h
6个回答
3
投票

您需要在文件上调用stat(2),然后在st_mode上使用S_ISREG宏。


23
投票

您可以使用便携式boost::filesystem(标准C ++库在最近在C ++ 17中引入std::filesystem之前无法做到这一点):

#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>
#include <iostream>

int main() {
    using namespace boost::filesystem;

    path p("/bin/bash");
    if(is_regular_file(p)) {
        std::cout << "exists and is regular file" << std::endl;
    }
}

3
投票

C ++本身并不处理文件系统,因此语言本身没有可移植的方式。特定于平台的示例是用于* nix的stat(如Martinv.Löwis所述)和用于Windows的GetFileAttributes

另外,如果你对Boost没有过敏,那就是相当平台的boost::filesystem


1
投票

在C ++ 17中,您可以使用std :: filesystem :: is_regular_file

#include <filesystem> // additional include

if(std::filesystem::is_regular_file(yourFilePathToCheck)) 
    ; //Do what you need to do

请注意,早期版本的C ++可能已经在std :: experimental :: filesystem下使用了它(来源:http://en.cppreference.com/w/cpp/filesystem/is_regular_file


0
投票

谢谢大家的帮助,我试过了

while ((dirp = readdir(dp)) != NULL) { 
   if (!S_ISDIR(dirp->d_type)) { 
        ... 
        i++; 
   } 
} 

它工作正常。 =)


0
投票
#include <boost/filesystem.hpp>

bool isFile(std::string filepath)
{
    boost::filesystem::path p(filepath);
    if(boost::filesystem::is_regular_file(p)) {
        return true;
    }
    std::cout<<filepath<<" file does not exist and is not a regular file"<<std::endl;
    return false;
}
© www.soinside.com 2019 - 2024. All rights reserved.