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;
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;
}
You may be wondering why your original code, with S_IFREG
and S_IFDIR
, worked on one operating system but not another. This is because the S_IFxxx
constants are optional in some revisions of the POSIX standard (this is the standard that specifies the contents of sys/stat.h
).
The S_ISxxx
function-like macros are required to be available, so it's better to use them when you can, but sometimes using the S_IFxxx
constants can make one's code much clearer. They are macros, so you can test for their presence with #ifdef S_IFREG
(if S_IFREG
is available, it's safe to assume the others are as well).
Some operating systems don't provide the S_IFxxx
constants by default, but do if you put #define _XOPEN_SOURCE 700
above all of your #include
lines. Linux is not normally one of those operating systems, but it becomes one of those operating systems if you use -ansi
or -std=cNN
on the compiler command line. (NB for reasons too complicated to get into here, it is usually a mistake to use those switches instead of -std=gnuNN
.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.