¿Cómo verifico si un archivo es un archivo normal?
-
11-07-2019 - |
Pregunta
¿Cómo verifico en C ++ si un archivo es un archivo normal (y no es un directorio, una tubería, etc.)? Necesito una función isFile ().
DIR *dp;
struct dirent *dirp;
while ((dirp = readdir(dp)) != NULL) {
if ( isFile(dirp)) {
cout << "IS A FILE!" << endl;
i++;
}
He intentado comparar dirp- > d_type con (unsigned char) 0x8, pero parece que no es portátil a través de diferentes sistemas.
Solución
Debe llamar a stat (2) en el archivo y luego usar la macro S_ISREG en st_mode.
Algo así (adaptado de esta respuesta ):
#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
}
Otros consejos
Puede usar el boost portátil :: sistema de archivos
(La biblioteca estándar de C ++ no podría haber hecho esto hasta la reciente introducción de std :: filesystem en 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;
}
}
C ++ en sí no se ocupa de los sistemas de archivos, por lo que no hay una forma portátil en el lenguaje en sí. Los ejemplos específicos de la plataforma son stat
para * nix (como ya lo señaló Martin v. L & # 246; wis) y GetFileAttributes
para Windows.
Además, si no eres alérgico a Boost , hay un impulso de bastante multiplataforma :: sistema de archivos
.
En C ++ 17, puede usar std :: filesystem :: is_regular_file
#include <filesystem> // additional include
if(std::filesystem::is_regular_file(yourFilePathToCheck))
; //Do what you need to do
Tenga en cuenta que la versión anterior de C ++ puede haberlo tenido bajo std :: experimental :: filesystem (Fuente: http://en.cppreference.com/w/cpp/filesystem/is_regular_file )
Gracias a todos por la ayuda, lo he intentado con
while ((dirp = readdir(dp)) != NULL) {
if (!S_ISDIR(dirp->d_type)) {
...
i++;
}
}
Y funciona bien. =)
#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;
}