clinuxlinux-kernelstat

S_ISDIR and S_ISREG undeclared despite including the <sys/stat.h> header


I am using the "S_ISDIR" and "S_ISREG" but am getting an error that they are undeclared. I tried using it in macOS(using S_IFDIR and S_IFREG) and it worked but not in linux terminal.

error: ‘S_ISDIR’ undeclared (first use in this function)  
error: ‘S_ISREG’ undeclared (first use in this function); did you mean ‘S_ISDIR’?  
struct stat s;
if(stat(fileName, &s) == 0 )
{
    if( s.st_mode & S_ISDIR )
    {
        return false;
    }
    else if( s.st_mode & S_ISREG )
    {
        return true;
    }
    else
    {
        return false;
    }
}
else
{
    return false;
}
return false;

Solution

  • You're using the macros incorrectly. They're function-like macros which accept the mode as a parameter:

    if( S_ISDIR(s.st_mode) )
    {
        return false;
    }
    else if( S_ISREG(s.st_mode) )
    {
        return true;
    }
    else
    {
        return false;
    }