How do i check if a file is a regular file?
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;
}
}
You need to call stat(2) on the file, and then use the S_ISREG macro on st_mode.
Something like (adapted from this answer):
#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
}
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
.