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 进行比较,但它似乎无法通过不同的系统进行移植。

4

6 回答 6

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;
    }
}
于 2008-11-30T15:31:59.547 回答
8

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

类似的东西(改编自这个答案):

#include <sys/stat.h>

struct stat sb;

if (stat(pathname, &sb) == 0 && S_ISREG(sb.st_mode))
{
    // file exists and it's a regular file
}
于 2008-11-30T15:21:42.813 回答
3

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

此外,如果您对Boost不过敏,那么它还有相当多的跨平台boost::filesystem

于 2008-11-30T15:27:26.813 回答
3

在 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 )

于 2017-12-17T12:12:42.510 回答
0

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

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

它工作正常。=)

于 2008-11-30T18:26:26.700 回答
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;
}
于 2013-12-19T08:45:30.810 回答