views:

958

answers:

4

How do i check in C++ if a file is a regular file (and is not a directory, a pipe, etc.)? I need a function isFile().

DIR *dp;
struct dirent *dirp;

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

I've tried comparing dirp->d_type with (unsigned char)0x8, but it seems not portable through differents systems.

+5  A: 

You need to call stat(2) on the file, and then use the S_ISREG macro on st_mode.

Martin v. Löwis
+2  A: 

C++ itself doesn't deal with file systems, so there's no portable way in the language itself. Platform-specific examples are stat for *nix (as already noted by Martin v. Löwis) and GetFileAttributes for Windows.

Also, if you're not allergic to Boost, there's fairly cross-platform boost::filesystem.

atzz
+9  A: 

You can use the portable boost::filesystem (The standard C++ library can't do this):

#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;
    }
}
Johannes Schaub - litb
A: 

Thank you all for the help, i've tried with

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

And it works fine. =)

Emilio