Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i check if a file is a regular file?

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.

like image 367
Emilio Avatar asked Nov 30 '08 15:11

Emilio


1 Answers

You can use the portable boost::filesystem (The standard C++ library could not have done this up until recent introduction of std::filesystem in C++17):

#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;
    }
}
like image 66
Johannes Schaub - litb Avatar answered Sep 17 '22 23:09

Johannes Schaub - litb