show the code first
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int is_reg_file(const char *path)
{
struct stat statbuf;
stat(path, &statbuf);
// test for a regular file
if (S_ISREG(statbuf.st_mode))
return 1;
return 0;
}
int is_dir(const char *path)
{
struct stat statbuf;
stat(path, &statbuf);
if (S_ISDIR(statbuf.st_mode))
return 1;
return 0;
}
stat
structure is defined as following, details can be found in stat(2)
manual.
struct stat {
dev_t st_dev; /* ID of device containing file */
ino_t st_ino; /* Inode number */
mode_t st_mode; /* File type and mode */
nlink_t st_nlink; /* Number of hard links */
uid_t st_uid; /* User ID of owner */
gid_t st_gid; /* Group ID of owner */
dev_t st_rdev; /* Device ID (if special file) */
off_t st_size; /* Total size, in bytes */
blksize_t st_blksize; /* Block size for filesystem I/O */
blkcnt_t st_blocks; /* Number of 512B blocks allocated */
...
};
The file type defined in st_mode
can be found in inode(7)
manual along with some macros.
POSIX refers to the stat.st_mode bits corresponding to the mask S_IFMT (see below)
as the file type, the 12 bits corresponding to the mask 07777 as the file mode bits
and the least significant 9 bits (0777) as the file permission bits.
The following mask values are defined for the file type:
S_IFMT 0170000 bit mask for the file type bit field
S_IFSOCK 0140000 socket
S_IFLNK 0120000 symbolic link
S_IFREG 0100000 regular file
S_IFBLK 0060000 block device
S_IFDIR 0040000 directory
S_IFCHR 0020000 character device
S_IFIFO 0010000 FIFO